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?
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With