0

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

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

This article here ... http://jupiterjs.com/news/why-you-should-never-use-jquery-live ... has convinced me to avoid live in favor of delegate.

With delegate, your jquery would look something like ...

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

Comments

-1

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.