I understood your question as such:
The first clicked item always keeps the class active2
and any other clicked item gets the class active
(removing active
from the previously clicked one).
A solution would look like this:
- If there is no item in the list with class
active
, none was selected before, so you add active
to the current one.
- If there is one, but no element has class
active2
, add active2
to the item with class active
, remove active
and add it to the current item.
- If both,
active
and active2
exist, remove active
from that item and add active
to the current one.
This would look like this in code:
var $lis = $("#myList li");
$('#myList').on('click', 'li', function() {
if($lis.hasClass('active')) {
if(!$lis.hasClass('active2')) {
$lis.filter('.active').toggleClass('active active2');
}
else {
$lis.filter('.active').removeClass('active');
}
}
$(this).addClass('active');
});
Alternatively, since after the second time an item was clicked, there will always be elements items with these classes, you could also simply use flags instead of searching for the elements over and over again.