Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery functionality not working after AJAX call

Tags:

html

jquery

ajax

I seem to be having an issue with a jQuery click function, I have the following code:

j$(document).ready(function(e) {

setInterval(function(){

    j$.ajax({
      url: "/include/new_customer.php",
      cache: false
    })
      .done(function( html ) {
        j$( "section .col-xs-12" ).append( html );
      });


  },80000);

    j$('a.dropDown').click(function(e){
        e.preventDefault();
        j$(this).closest('.row').next().toggleClass('hidden');
    });
});

with the following HTML ( grabbing what's necessary):

<div class="col-xs-12>
    <div class="row">
        <a href="#" class="dropDown">Manage</a>
    </div>
    <div class="row hidden">
        <!-- stuff -->
    </div>    
</div>

You can see if you click the a tag, the row with the class hidden will toggle. I have AJAX that appends another 2 rows so it will be like so:

<div class="col-xs-12>
        <div class="row">
            <a href="#" class="dropDown">Manage</a>
        </div>
        <div class="row hidden">
            <!-- stuff -->
        </div>  
        <div class="row">
            <a href="#" class="dropDown">Manage</a>
        </div>
        <div class="row hidden">
            <!-- stuff -->
        </div>    
    </div>

My problem is that with the new data, when I click on the a tag, the toggle functionality doesn't work. I have done some tests such as removing the class hidden from inspect element and there is data to display. I don't know what's going on. Please help!

like image 933
Akira Dawson Avatar asked Apr 17 '14 01:04

Akira Dawson


1 Answers

You need to use event delegation to attach events for dynamically loaded elements:

j$(document).on('click','a.dropDown',function(e){
    e.preventDefault();
    j$(this).closest('.row').next().toggleClass('hidden');
});
like image 191
Felix Avatar answered Nov 15 '22 08:11

Felix