Biraj Dahal
Biraj Dahal

Reputation: 57

Jquery Function Not Working After Adding a Class. How Can I fix this?

I have written an HTML Code with jquery for test

$('.alert').click(function(){
  alert("alert");
});

$('.secondButton').click(function() {
  $('.thirdButton').addClass('alert');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

<button class="alert">Button A</button>
<button class="secondButton">Button B</button>
<button class="thirdButton">Button C</button>

Now here when the button containing class alert (Button A) is clicked alert events occur that is fine.

Now When I click the second button, it adds the class alert class to Button C. Now the button C has class alert, but when I click Button C the alert evert doesn't occur. How Can I fix this?

jsFiddle

Upvotes: 0

Views: 375

Answers (1)

trincot
trincot

Reputation: 350280

This happens because the jQuery collection of elements that have the "alert" class is determined when the main script runs, and only those will get the appropriate click handler assigned to them. At that moment there is only one such element. If later the class is also given to another element, this will not dynamically attach the click handler to that element too.

The solution is event delegation. Listen to click events that bubble up to an element that is higher up the DOM tree, like body, and check that the click event originated at an element that at that moment had the class "alert".

In jQuery the syntax for such event delegation is demonstrated here:

$("body").on('click', '.alert', function() {
  alert("alert");
});

$('.secondButton').click(function() {
  $('.thirdButton').addClass('alert');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button class="alert">Button A</button>
<button class="secondButton">Button B</button>
<button class="thirdButton">Button C</button>

Upvotes: 1

Related Questions