Question

I have a Facebook-like page with posts and comments. I have a Reply link on every post that, when clicked, should move the cursor to that post's comment form's text area, and it does. I just use

$('.reply-link').parents('article').find('textarea').focus();

However, I also have infinite scroll working on this page and that wraps appended articles in its own wrapper div.

My problem is that my reply links don't work for any article that's within that wrapper div loaded by infinite scroll. I have a JSFiddle which demonstrates this.

http://jsfiddle.net/Lp2kG/

If someone can explain to me why that is and how to handle this correctly I'd appreciate it. Thanks!

Was it helpful?

Solution

When you append new content, that new content does not have any event handlers. To have event handlers for new content you must either set the event handlers after the content is added or use delegated event handling on a static parent.

In this case, the closest common static parent (in your jsFiddle) is the body so you can install the click handler there and then use the delegated form of .on() like this .on('click', selector, fn).

You can switch to delegated event handling by changing your event handling code from this:

jQuery('.reply-link').unbind().click(function() {
   $(this).parents('article').find('textarea').focus(); 
});

to this:

jQuery(document.body).on('click', '.reply-link', function() {
   $(this).parents('article').find('textarea').focus(); 
   return false;
});

Note, this also prevents the default behavior for the link by returning false from the jQuery event handler.

Working demo: http://jsfiddle.net/jfriend00/ah8gX/

OTHER TIPS

I see two issues. One you need a prevent default so the link doesn't do it's default action # which would scroll to the top of the page.

Also, there is no click event assigned to the links that are added after the initial binding. You just need to re-bind them. The easiest option is to just do it in a function and call it again after append like this:

function assignListeners(){
    jQuery('.reply-link').unbind().click(function(e) {
        e.preventDefault();
       $(this).parents('article').find('textarea').focus(); 
    });
}

updated fiddle: http://jsfiddle.net/Lp2kG/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top