Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use addClass and removeClass repeatedly on a single element?

Tags:

So what I want to achieve is just change the classes of a HTML link on every click like this:

  • Remove .first class if it is present, then add .second class
  • Remove .second class if it is present, then add .third class
  • Remove .third class if it is present, then add .fourth class
  • And so forth...

No luck so far. What could I be doing wrong?

Here's the single line of HTML code where I'm trying my jQuery code on:

<a class="first" href="#">Test 1</a>

Here's my jQuery:

$( "#menu li a.first" ).click(function() {

   $( "#menu li a.first" ).removeClass("first").addClass("second");

}

$( "#menu li a.second" ).click(function() {

   $( "#menu li a.second" ).removeClass("second").addClass("third");

}

$( "#menu li a.third" ).click(function() {

   $( "#menu li a.second" ).removeClass("third").addClass("fourth");

}

Thanks in advance!

like image 837
jakestack Avatar asked Mar 09 '16 09:03

jakestack


1 Answers

The problem is you're trying to attach the event handler before it even has the class second or third.

Besides this approach is pretty verbose. I suggest simply providing an array of classes. Like so:

var classNames = ['first', 'second', 'third'];

Then add a different identifier to the button, for instance add a class class-changer. And attach the following event handler.

$('.class-changer').on('click', function() {
    var $el = $(this)
    for (var i= 0; i < classNames.length; i++) {
        if ($el.hasClass(classNames[i]) && classNames[i+1]) {
           $el.removeClass(classNames[i]).addClass(classNames[i+1]);
           break;
        }
    }
});
like image 165
GMchris Avatar answered Nov 01 '22 15:11

GMchris