javascriptjqueryclassjquery-ui

Switching between two different classes jQuery


Having trouble getting the following code to work:

$('#changeMode').button().click(function(){
    $('#playfield').toggle(function() {
        $(this).switchClass("gridView","plainView");
    }, function() {
        $(this).switchClass("plainView","gridView");
   });      
});

I cannot get it to switch the following div's class.

<div id="playfield" class="gridView"></div>

Any ideas?

EDIT: I tried this:

$('#changeMode').button().click(function(){
    if ($('#playfield').attr('class') == "gridView"){
        $('#playfield').removeClass("gridView");
        $('#playfield').addClass("plainView");
    } else {
        $('#playfield').removeClass("plainView");
        $('#playfield').addClass("gridView");
    }
});

And it seems to work fine, what the heck?


Solution

  • I wasn't aware of a switchClass, perhaps you were thinking of toggleClass? Anyways - I had some old code that used this (I was having some strange issues with toggleClass):

    $(this).removeClass("gridView").addClass("plainView"); 
    
    or
    
    $(this).toggleClass("gridView plainView");
    

    and vice versa.

    Example:

    $('#changeMode').button().click(function(){
        $('#playfield').toggle(function() {
            $(this).toggleClass("gridView plainView");
            //$(this).removeClass("gridView").addClass("plainView"); 
        }, function() { 
            $(this).toggleClass("plainView gridView");
            //$(this).removeClass("plainView").addClass("gridView"); 
       });      
    });
    

    But as others have suggested toggleClass should work for your needs.