Alex Rivera | Logout

jQuery click() still being triggered after .clickable class is removed

Asked 2012-08-16T09:16:06.600
23

I've got a click event assigned to a div of a particular class. When the click occurs, the class is removed from the div. However, you can still click the div and the click() event is triggered (even though the class has since been removed). Here's an example:

HTML:

<div class="clickable">
  <p>Click me</p>
</div>

JavaScript/jQuery:

$('.clickable').click(function() {
  $(this).removeClass('clickable');
  $(this).addClass('not-clickable');
  alert('Clicked!');
});

I can see the classes are removed and added (as the colour of the text changed as per my CSS). However, you are still able to click the div multiple times and the alert() will still appear.

This also seems to occur in reverse; so if I add the clickable class to a div, the code in $('.clickable').click(function() {...}); doesn't run (but visually, the div changes as per the new styles).

How can I make it so that the click events match up to the classes, even after jQuery adds/removes the clickable class?

Edit
Report

2 Answers

3
$(document).on('click', '.clickable', function() {
  $(this).removeClass('clickable');
  $(this).addClass('not-clickable');
  alert('Clicked!');
});
answered 2012-08-16T09:20:11.360
0

Your understand of even assignment is a bit wrong. Please read your code

$('.clickable').click(function()
  1. Find element with the class '.clickable'
  2. Assign onclick handler to the element

See, it's the element that get's handler, not the class name. You need to remove the handler. For that you can try:

$('.clickable').click(function() {
    $(this).removeClass('clickable');
    $(this).addClass('not-clickable');
    alert('Clicked!');
    $(this).unbind('click');
});
answered 2012-08-16T09:23:06.280

Your Answer