Tadas V.
Tadas V.

Reputation: 835

Jquery - Button does not fire properly with class

Here is a sample code:

$("#item > button:not(.finished)").on("click", function() {
  console.log("fired");
  $(this).addClass("finished");
})

$("#item > button.finished").on("click", function() {
  console.log("finished");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item">
  <button type="button" class="">Text</button>
</div>

For some reason it always logs "fired. Even if the class is added. What am I not seeing??

Note: button is NOT dynamic.

Upvotes: 0

Views: 58

Answers (1)

Yousaf
Yousaf

Reputation: 29312

Reason why your code is not working as you expect is pointed out by David Thomas in the comment

Events are bound to the nodes matching the selector when the code is run, changing the classes after the events are attached makes no difference to that event-binding

that's why you always see fired logged to the console

Here's a simplified version of your code that works as you expect it to.

$("#item > button").on("click", function(e) {

  if(!(e.target.classList.contains('finished'))) {
      $(e.target).addClass("finished");
      console.log("fired");
  } else {
      console.log("finished");
  }

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="item">
  <button type="button" class="">Text</button>
</div>

Upvotes: 1

Related Questions