Reputation: 7752
I have a FAQ page which questions open up to reveal answers and display a little plus or minus icon depending on weather the question has been click on to open or close it.
I can achieve this action by adding classes to the element which has been clicked to show weather it has been opened are not.
$( ".faq-question" ).click(function(){
if(!($(this).hasClass("open"))){
$(this).addClass('open');
$('span.icon', this).html('-');
}else{
$(this).removeClass('open');
$('span.icon', this).html('+');
}
});
I'm wondering if there is a in-built toggle function for jQuery or JavaScript which aslo achieves this? I see that the jQuery toggle() event is depreciated and there are plenty of suggestions online on how to achieve this with custom scripts but what is the best way, is the method of adding classes to the HTML ok? Why was the toggle function removed? It seemed very useful.
Upvotes: 0
Views: 2109
Reputation: 193311
Your approach works, but it has disadvantage is that JS code becomes obtrusive because of +/-
symbols in it. Normally you don't want presentation to be mixed with javascript code. You can try this instead:
$( ".faq-question" ).click(function() {
$(this).toggleClass('open');
});
And move presentation to CSS:
.faq-question .icon:after {
content: '+';
}
.faq-question.open .icon:after {
content: '-';
}
If tomorrow you want to use plus/minus icons instead of "+/-" chars, you will not need to touch javascript code at all.
Upvotes: 2
Reputation: 15393
Use .toggleClass
in jquery
$( ".faq-question" ).click(function(){
$(this).toggleClass('open');
var symbol = ($(this).hasClass('open')) ? '-' : '+';
$('span.icon', this).html(symbol);
});
Upvotes: 1