user3573535 user3573535 - 2 months ago 12
jQuery Question

Jquery - Can I undo event on previous element?

I wanted to ask, if possible to undo action on previous element which fired some event.

To illustrate my question we may use:

HTML :

<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>


jQuery :

$('a').on('click',function(e) {
$(this).addClass('ok');
// looking a way to manipulate previous <a> which fired event, before i will add class to $(this)
});


If I click first
<a>
it will add ok class. And all I want to remove this class from on clicking second
<a>
.

So I click first
<a>
and it has ok class. Next I click second
<a>
and second has now ok class but not first one (I called this action Undo).

And is I click third
<a>
, previous clicked
<a>
should not have ok class. I hope it's clear.

Thanks for advice.

Answer

just add the following line after you add the class,

$("a").not(this).removeClass("ok");

so finally your click event function should look like,

$('a').on('click',function(e) {
  $(this).addClass('ok');
  $("a").not(this).removeClass("ok");
});

it will add ok class on the clicked item, and then remove ok class from any 'a' which is not the clicked one.