Edward1442
Edward1442

Reputation: 143

jQuery make addClass clickable

I have an li which, using jQuery when clicked adds the class "active":

$('li').click(function() {
    $(this).addClass('active');
});

I then want the class to be removed once it is clicked again:

 $('.active').click(function() {
    $(this).removeClass('active');
});

However nothing happens on click, I imagine this is because the class didnt exist in the first place, I am using $(document).ready();

Is there any way of accessing an added variable, or am I missing something really obvious which is causing nothing to happen when clicking on the added class?

Upvotes: 1

Views: 40

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because the .active class is amended at runtime, therefore you cannot bind any event handlers to it on load of the page. To solve this you could use a delegated event handler instead:

$('ul').on('click', 'li', (function() {
  $(this).toggleClass('active');
});

Note that this will replace both the event handlers in the code of your question.

Upvotes: 5

Related Questions