You are here

Javascript click calls and AJAX

When you're updating content on a page through an AJAX call like jQuery's $.getJSON, don't forget to refresh any potential javascript or jquery event calls (click, etc) that might be attached to the new content.  I spent some hours trying to sort out why the existing click functions weren't working on back and next buttons that I was getting from a getJSON call to one of my Drupal sites.  The existing click event was being attached on the buttons class in the original page build but new buttons with that same class were being created in the getJSON call and needed the funtions to be re-attached.  I set up a separate function, triage_clicks to set the click code.  So just remember that .click() functions set up and loaded on the page build won't be available to new items of the same class or id that come via AJAX calls.function triage_getdata(url){        triage_loading();        $.getJSON( url, function( data ) {          if (data){              out = out + data ;          }          $(".triage-content").html(out);          triage_clicks();          $(".triage-loading").remove();      }); }function triage_clicks(){        // unsets click and touchstart functions so that we don't get doubles        $('.triage-row').unbind();        $('.triage-row').die("touchstart click");        $('.triage-row').live('touchstart click', function(e){            my_havascript_code...         });}