Question

So I am using jquery .load to automatically refresh a DIV within a page.

var refreshId = setInterval(function() {loadAdminTab()}, 30000);

});

function loadAdminTab(){
    $( "#maintab" ).load( "admintab2.php", function() {
        $('#loadingsq').fadeOut(0);
    });
}

I also run the "loadAdminTab" in the $(document).ready load. On the initial load all functions within the loaded DIV work fine. However, after the first interval runs. Certain functions within the loaded DIV stop working.

Such as this:

< input type="button" id="showdivitem1" value="Button" ><br>
< div id="item1" style="display:none;" >Div Display</div>

<script>
  $('#showdivitem1').mousedown(function(){
     $('#item1').show();
  });
</script>

Like I said, after the page initially loads, all is well, but once the subsequent .loads run, the $('#item1').show(); will NOT work for the life of me.

Something is being reset within the loaded document and div.


Here is my exact code, and it's still not firing within the #maintab. Again this code is within the maintab, not outside in a parent, is the problem?

$('#maintab').on('mousedown','#transferCall<?php echo $callid; ?>', function(){
    $('#transfer<?php echo $callid; ?>').css('display','block');
}); 
Was it helpful?

Solution

Since you're rewriting the content into the #maintab, all events handlers you defined once at DOMready - for nodes inside it - can't work if a new request change its content (even if the new elements injected inside that container are the same: the handlers defined were attached to nodes that no longer exist).

So you need to use event delegation and capture your events on the #maintab (or on a parent element)


E.g. your example becomes

$('#maintab').on('mousedown', '#showdivitem1', function(){
   $('#item1').show();
});

You're setting the handler to #maintab (that node is not removed at every ajax request) and this captures the propagation of a mousedown event in #showdivitem1 element

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