Skip to content Skip to sidebar Skip to footer

JQuery Switching Between More Than Two Classes

I've already posted a question about jQuery toggle method here But the problem is that even with the migrate plugin it does not work. I want to write a script that will switch bet

Solution 1:

The thing is that your code will hook your handlers to the elements with those classes when your code runs. The same handlers remain attached when you change the classes on the elements.

You can use a single handler and then check which class the element has when the click occurs:

$('div#priority'+id).on('click', function() {
    var $this = $(this);
    if ($this.hasClass('priority')) {
        $this.removeClass('priority').addClass('priority-low');
    }
    else if (this.hasClass('priority-low')) {
        $this.removeClass('priority-low').addClass('priority-medium');
    }
    else /* ...and so on... */
});

You can also do it with a map:

var nextPriorities = {
    "priority":           "priority-low",
    "priority-low":       "priority-medium",
    //...and so on...
    "priority-emergency": "priority"
};
$('div#priority'+id).on('click', function() {
    var $this = $(this),
        match = /\bpriority(?:-\w+)?\b/.exec(this.className),
        current = match && match[0],
        next = nextPriorities[current];
    if (current) {
        $this.removeClass(current).addClass(next || 'priority');
    }
});

Solution 2:

I have tried myself to do this with the sole help of toggleClass() and didn't succeeded. Try my method that declares an array with your five classes and toggles dynamically through them.Do adapt to your own names.

//variable for the classes array
var classes=["one","two","three","four","five"];
//add a counter data to your divs to have a counter for the array
$('div#priority').data("counter",0);
$(document).on('click','div#priority',function(){
    var $this=$(this);
    //the current counter that is stored
    var count=$this.data("counter");
    //remove the previous class if is there
    if(($this).hasClass(classes[count-1])){
        $(this).removeClass(classes[count-1]));
    }

    //check if we've reached the end of the array so to restart from the first class.
    //Note:remove the comment on return statement if you want to see the default class applied.
    if(count===classes.length){
        $this.data("counter",0);
        //return;//with return the next line is out of reach so class[0] wont be added
    }
    $(this).addClass(classes[count++]);
    //udpate the counter data
    $this.data("counter",count);
});
//If you use toggleClass() instead of addClass() you will toggle off your other classes.Hope is a good answer.

Post a Comment for "JQuery Switching Between More Than Two Classes"