0

As I've discovered with Ajax in jQuery, loaded elements are not jQuery objects. What's the best way to 'rescan' the document to make elements loaded with Ajax jQuery objects?

In the code below jq('.storyBlock button').click(function() and the other functions do not fire on the loaded Ajax html. How best to change this code so they will fire?

var jq = jQuery.noConflict();

jq(document).ready(function() {
    // Disable buttons after clicking
    jq('.storyBlock button').click(function() {
        jq(this).addClass('selected');
        jq(this).parent().addClass('disabled');
        jq(this).parent().find('button').attr('disabled', true);
    });
    // Event Handler
    jq('.storyBlock button').click(function() {
        // Find link
        var getID = jq(this).data('link');
        console.log(getID + '.html');

        // Load file and insert after last story
        jq.ajax(getID + '.html').done(function(html) {
        jq('#stories > div:last-child').after(html);
        if ( (getID) != 'start' ) {
            jq('html,body').animate({ scrollTop: jq('#' + getID).offset().top },'slow');
        } else {
            jq('.storyBlock').remove();
            jq('#stories > div' ).load( "start.html" );
            jq('html,body').animate({ scrollTop: jq('#start').offset().top },'slow');
        }
       });
    });
});
Filburt
  • 17,626
  • 12
  • 64
  • 115
Paul Redmond
  • 3,276
  • 4
  • 32
  • 52
  • 2
    [event delegation](http://learn.jquery.com/events/event-delegation/)!!! – Arun P Johny Feb 26 '14 at 12:25
  • @ArunPJohny is correct. If you're dynamically adding elements to the DOM you will need to use event delegation – heymega Feb 26 '14 at 12:30
  • @ArunPJohny I don't think it's useful to yell "event delegation!!!" at the OP and/or downvote this question even if the problem concerns a fundamental concept of the technology involved. – Filburt Feb 26 '14 at 12:33
  • @Filburt I didn't downvote... but the links provided will help solve the problem – Arun P Johny Feb 26 '14 at 12:36
  • Thanks for the quick replies. I'm still not sure how this function can be applied to my code above to make it work. Something like this: `$(document).on( load, function(){} );` ? – Paul Redmond Feb 26 '14 at 12:36
  • you need to change the event registration to `jq(document).on('click', '.storyBlock button', function() {..})` – Arun P Johny Feb 26 '14 at 12:37
  • @ArunPJohny - Ah, by adding that and removing the click function inside, it now behaves as expected. This function is very useful to know. Thanks. If you want to add that as the answer I will mark as correct - thank you. – Paul Redmond Feb 26 '14 at 12:41
  • @PaulRedmond sure will do... (since there are no answers) – Arun P Johny Feb 26 '14 at 12:45

1 Answers1

1

You need to use event delegation since you need to handler dynamic elements

So convert your event handlers to

jq(document).on('click', '.storyBlock button', function() {
})
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531