Skip to content Skip to sidebar Skip to footer

Swap Css Class

I would like to swap classes in two links using jQuery. I got a HTML code like:
AAA

Solution 1:

Solution 2:

Use .toggleClass() instead of checking if the class is there, and then either adding or removing it. .toggleClass() already takes care of that logic for you.

Your code would be:

$('#showHide1').click(function() {
    $("#aaa")
        .toggleClass("hide")
        .toggleClass("hide");
    $("#bbb")
        .toggleClass("hide")
        .toggleClass("hide");
});

Note: This assumes that the show and hide classes start off in the correct state.

Solution 3:

I think youve got you id's and classes mixed up try this html:

<divid="showHide1"><aclass="show aaa">AAA</a><aclass="hide bbb">BBB</a></div><divid="showHide2"><aclass="show aaa">AAA</a><aclass="hide bbb">BBB</a></div>

js:

$('#showHide1, #showHide2').click(function() {
    var a_showing = $('.aaa.show', this);
    var a_hiding  = $('.aaa.hide', this);
    var b_showing = $('.bbb.show', this);
    var b_hiding  = $('.bbb.hide', this);
    a_showing.addClass('hide').removeClass('show')
    a_hiding.addClass('show').removeClass('hide')
    b_showing.addClass('hide').removeClass('show')
    b_hiding.addClass('show').removeClass('hide')
});

fiddle: http://jsfiddle.net/maniator/qMBRq/

Solution 4:

This is how I would do it.

HTML

<divclass="showhide"><aid="aaa1"class="show">AAA</a><aid="bbb1"class="hide">BBB</a></div><divclass="showhide"><aid="aaa2"class="show">AAA</a><aid="bbb2"class="hide">BBB</a></div>

JavaScript

$(function() { 
    $('a.hide').hide();
    $('div.showhide').click(function() {
        $(this).children('a').toggle();
    });
});

This way, if the user doesn't have JavaScript enabled, they'll still be able to see everything. It may cause a flash of unstyled content (not exactly, but basically) since you're adding the hide after the DOM is ready via JavaScript. Now, that may or may not be important for you so you'll have to decide.

Post a Comment for "Swap Css Class"