Swap Css Class
Solution 1:
To expand of cdeszaq's answer, instead of having .show
and .hide
only use .hide
then you can use the following:
HTML:
<div id="showHide1" class="showHide">
<a id="aaa">AAA</a>
<a id="bbb" class="hide">BBB</a>
</div>
<div id="showHide2" class="showHide">
<a id="aaa">AAA</a>
<a id="bbb" class="hide">BBB</a>
</div>
CSS:
.hide {
display: none;
}
JS:
$('.showHide').click(function() {
$('a', this).toggleClass('hide'); //I had inverted my selector and context earlier, this is correct
});
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')
});
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"