Crys Ex
Crys Ex

Reputation: 335

Multiple JS load and execution in a feed

I have the following code:

$('.replay_text').keydown(function(event) {
    if (event.keyCode == 13) {
        pid = $(this).attr('postid');
        addCom('tix_'+pid);
        return false;
     }
     });

Which adds a comment each time I enter text in a specific textarea. The problem is that I need to include this JS multiple times on a page (I am loading a feed with content) so as I scroll down it's loaded 2-3 times. What happens is that once I enter a comment and submit it, it's added 2-3 times (the number of times it was loaded).

If I only load it once it won't work for the other feed content that is loaded dynamically (appended via jQuery).

Is there any solution for this problem? I tried including the JS once on top of the document but then it doesn't work at all, NOTE: all the feed content is loaded dynamically.

Thank you

Upvotes: 1

Views: 31

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Use a delegated event. Then you can attach the handler once, and it will work for all elements appended dynamically:

$(document).on('keydown', '.replay_text', function(event) {
    if (event.keyCode == 13) {
        pid = $(this).attr('postid');
        addCom('tix_'+pid);
        return false;
     }
 });

Upvotes: 1

Related Questions