0

I'm in the process of loading a view different info panels using jquery's .load() function. However, some of the content in the loaded element which I'd like to interact with (using .on('click')) doesn't seem to be responding accordingly. Can I have click actions on dynamically loaded content? If not, what's the best work around? #updateJSON is an that lives within the viewjson.php file.

$().ready(function() {

$("#viewlatestjson").load("viewjson.php");
$("#viewlivedatafeeds").load("viewfeed.php");

$('#updatejson').on('click', function(e){
    e.preventDefault();
    $("#alertPanel").removeClass( "success warning info alert secondary" );
    $("#alertPanel").addClass( "secondary" );
    $("#alertMessage").html( "<img src=\"icons/alert-loader.gif\"> Updating local JSON conversion, please wait..." );
    $("#alertPanel").fadeIn(300);
    $.ajax({
        url: 'downloadjson.php',
        type: 'post',
        data: {'update': 'yes'},
        success: function(data, status) {
            if(data == "complete") {
                setTimeout(function(){
                    $("#alertPanel").removeClass( "success warning info alert secondary" );
                    $("#alertPanel").addClass( "success" );
                    $("#alertMessage").html( "JSON conversion complete. You now have the latest pull." );
            }, 3000);
        }   
        else if(data == "notime") {
            setTimeout(function(){
                $("#alertPanel").removeClass( "success warning info alert secondary" );
                $("#alertPanel").addClass( "info" );
                $("#alertMessage").html( "Cannot Update: You are only allowed to update every 20 minutes." );
            }, 3000);   
        }
      }
    });
});});
radiantstatic
  • 342
  • 4
  • 20
  • you can have `click` on dynamic content, what does your html for `#updatejson` look like (parent wrappers too) – depperm Jul 23 '15 at 17:34
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – depperm Jul 23 '15 at 17:35

2 Answers2

0

Try passing a function that adds the click handler as a callback to the load function, so you know the element is there before you try and apply a click handler to it.

$("#viewlivedatafeeds").load("viewjson.php",function(){
    $('#updatejson').on('click', function(e){
        e.preventDefault();
        /*
        .
        .
        .
        */
    }
});
mpallansch
  • 1,174
  • 6
  • 16
0

Figured it out. I must add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

$(document.body).on('click', '#viewlatestjson' ,function(){})
radiantstatic
  • 342
  • 4
  • 20