1

I'm building a Django Application and stuck at the JQuery issue. When I click on the Paragraph with class 'select' it triggers the jQuery click event, the issue is when I change the class name from 'select' to 'selected' using JQuery, it still triggers the 'select' class click event whereas it is supposed to not be called after removing the 'select' class. Here is the sample code:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".select").on('click', function(){
  $(this).addClass('dont_select')
  $(this).removeClass('select');
  alert("Click event called")
  });
});
</script>
</head>
<body>

<p class='select'>Change Class Using Jquery</p>



</body>
</html>

Can someone please explain the solution?

I_love_vegetables
  • 1,575
  • 5
  • 12
  • 26
ASIF
  • 121
  • 1
  • 8
  • 1
    You need to remove the event listener; changing the class doesn't automatically removes the event listener. Alternate option is to check which class `p` element has and take appropriate action based on the class `p` element has. – Yousaf Jun 05 '21 at 10:45
  • 2
    That's the expected behavior. When you attach the event, removing a class won't remove the attached event automatically. You could attach the click event to the closest common parent element of `.select` elements, and use [event delegation](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) to attach the events. – Teemu Jun 05 '21 at 10:46
  • 1
    Event listeners get added to the element(s) that match that selector at the time. The element still exists even when you remove the class – charlietfl Jun 05 '21 at 10:49
  • 1
    Exactly, `$(".select")` simply grabs a list of elements that match at the time the command runs; the selection doesn't extend into the future. –  Jun 05 '21 at 10:49
  • 1
    Unless dynamic elements will be added, you can do this: https://jsfiddle.net/d96pucvh/ –  Jun 05 '21 at 10:52
  • 1
    @Teemu solution worked. Event Delegation fixed the issue. The updated JQuery script is: Thank you everyone for helping. You guys are great :D – ASIF Jun 05 '21 at 10:53
  • 1
    You can also simply remove it as follow, in your script instead of adding/removing class: ```$(this).off('click');``` – prettyInPink Jun 05 '21 at 10:56

0 Answers0