Reputation: 2559
Using jQuery, I add/remove a class from my menu using toggleClass()
I want to know if the class was added or removed. I read that there is a second parameter state but this seems to be to specify wether to only add or remove rather than return what was actually done
I need something like this
$el.toggleClass(sidebarCollapsed, addOrRemove);
if (addOrRemove) {
sessionStorage.setItem("sidebarState", "collapsed");
} else {
sessionStorage.setItem("sidebarState", "expanded");
}
Can I do this using toggleClass or will I have to check for the class using hasClass()
and then add/remove accordingly?
Upvotes: 3
Views: 1348
Reputation: 24965
You could potentially inline your logic with a ternary.
sessionStorage.setItem(
"sidebarState",
$el.toggleClass(sidebarCollapsed).hasClass(sidebarCollapsed) ? "collapsed" : "expanded"
);
Upvotes: 0
Reputation: 1428
The short answer to your question is no, the toggleClass
method does not contain that functionality on its own. It is only for toggling the class, and does not have any callback that does what you want.
As shown in the docs, the parameters it accepts all relate to which class to toggle: http://api.jquery.com/toggleclass/
The return type of the method is shown as "Returns: jQuery", which indicates the method returns the jQuery object / collection that was acted upon. So you can check what the result of the operation was, for example:
var result = $('div').toggleClass('foo');
console.log('Was the class added? ' + result.hasClass('foo'));
Upvotes: 4