Jquery .click not finding class

Matthew B
Matthew B used Ask the Experts™
on
I have a button that on click makes an ajax call and returns another subset of buttons like an accordion. This works perfectly.

Now, if the user clicks one of these subset of buttons (active-client), i want it to return another list below that item. I cant seem to get the jquery selector to even pick up on the second click, what am i doing wrong?

HTML
<div class="period-wrapper">
<!-- When user clicks this button it returns the data below -->
<button class="accordion today active" data-attribute="today">30<br>Today</button>

<!-- We found some data! -->
<div class="client-wrapper">
<!-- If i click this button i want to do some stuff not even getting any errors-->
<button class="accordion active-child" data-attribute="3077">8<br>Client_1</button>
<div class="card-wrapper"></div>
<button class="accordion active-child" data-attribute="33">5<br>Client_2</button>
<div class="card-wrapper"></div>
/div>

</div>

Open in new window


JQUERY

$('.accordion.active-child').click(function(e) { 

console.log($(this).data('attribute'));

});

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
Your jQuery fires when the page first loads, so this code:

$('.accordion.active-child').click(function(e) {

only runs when the page is first loaded. At that point it will bind the click event to all the .active-child elements it finds. Once you click your button you are adding additional active-child elements to your page, so the code to bind the event has already been fired and these elements won't have the event handler bound to them.

To get around this you need to delegate the event handler to a different element - one that exists when your page first loads. Looking at your code above, it seems like the period-wrapper would be a good candidate for that, so you would need to change your code to the following:

$('.period-wrapper').on('click', '.accordion.active-child', function(e) {
    console.log($(this).data('attribute'));
});

Open in new window

This binds the event handler to the period-wrapper element, which will exist when the page first loads. The event will then fire when any .active-child elements are clicked on, whether or they existed on page load.
Matthew BHack

Author

Commented:
Always something! Thanks for the answer chris, you were 100percent right!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial