5

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!

Akira Dawson
  • 1,247
  • 4
  • 21
  • 45
  • 1
    possible duplicate of [In jQuery, how to attach events to dynamic html elements?](http://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – dsgriffin Apr 17 '14 at 01:36
  • Cheers for that. I had no idea what to search for for my problem! – Akira Dawson Apr 17 '14 at 01:44

1 Answers1

13

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');
});
Felix
  • 37,892
  • 8
  • 43
  • 55
  • 2
    You bloody beauty mate. This is what I needed for it to work. I just didn't know what to search on Google, thanks a million! – Akira Dawson Apr 17 '14 at 01:43