sxv
sxv

Reputation: 275

jQuery does not execute on dynamically loaded content, even on a click events

I have two document.ready() functions. The first loads content into div#header. The second one performs a hide function and then a toggle function on the newly loaded content. I am not sure if this is a queueing issue or something, but not even the alert() below is executed when I click the loaded content. Thanks.

<script type="text/javascript">
$(document).ready(function() {
     $("#header").load("/documents/collegeradioheader.txt");
});
</script>
<script type="text/javascript">
 $(document).ready(function() {
    $(".hideme").hide(); 
    $(".slick-toggle").click(function() {
        alert('hi');
        $(this).parent().next('div').slideToggle('fast');       
    });
});
</script>

Edit: simplified code

Upvotes: 1

Views: 2547

Answers (2)

mu is too short
mu is too short

Reputation: 434945

The click binding is probably happening before the .load is finished. Try replacing your .click with a .live version:

$(".slick-toggle").live('click', function() {
    alert('hi');
    $(this).parent().next('div').slideToggle('fast');
});

Upvotes: 0

jerone
jerone

Reputation: 16881

Although the live is a working solution, there is an complete event in the AJAX load that fires when the load has finished.

<script type="text/javascript">
$(function() {
    $("#header").load("/documents/collegeradioheader.txt", function() {
        $(".hideme").hide(); 
        $(".slick-toggle").click(function() {
            alert('hi');
            $(this).parent().next('div').slideToggle('fast');       
        });
    });
});
</script>

Upvotes: 3

Related Questions