tags:

views:

32

answers:

2

I have this:

$('#wallCommentResponse' + wallID).append('<div class="userWallComment"><a id="showCommentLink' + wallID +'" class="showCommentLink" ref="'+ wallID +'" data-id="'+ howMany +'" style="cursor: pointer;">Hide comments</a></div>').show();

INSIDE the click function.

I have this to show a box, with the link "hide comments" at the bottom of all the comments. It shows it how i want to, but when i click nothing happens. And i have binded .showCommentLink to

        $('.hideWhenShowAll' + wallID).show(); 

I have another link, just like this, but is not showing by append() but normal HTML, that you also can click on "Hide comments" and it works very well, and its binded to the same function.

So something must be wrong when you append the link, inside the same function that the link triggers on click?

What is wrong? thank you

+3  A: 

Change your current .click(func) to .live('click', func), something like this:

$(".showCommentLink").live("click", function() {
  $('.hideWhenShowAll' + $(this).attr("ref")).show(); 
});

This will work for elements added later as well, via .append() or whatever other method, it's also cheaper when you have many elements. Currently your $(".showCommentLink") selector is finding elements, binding to them...if they were appended later they don't get the click handler, because the selector didn't find these new elements when it was run.

Nick Craver
thank you for explaining very well +1
Karem
A: 

I'd like to clear up Nick Craver's answer a bit more.

Once the DOM is loaded everything in...

$(document).ready(function(){
    //put js here
});

...is run. If you bind functions to elements, that happens to all then-existing elements. If you add other DOM elements and you want certain functions to bind to them, you can do one of two things. -manually bind them -use .live() as Nick Craver suggests, so binding of new DOM elements happens automagically.

Niels Bom
To be clear here, no additional binding happens with new elements and `.live()`, it's a completely passive event listener that relies on bubbling up to `document` (or another more local context, if specified), but it doesn't actually *do* anything when new elements are added.
Nick Craver