Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

toggle() vs toggleClass()

In jQuery, what is the use of these and how do I use them?

One more thing, what are these? I mean are these methods? or functions?

Thanks in advance

1 Answer

Steven Parker
Steven Parker
231,269 Points

Those are both pretty cool jQuery methods. A method is a function that is also an object property.

The toggle method makes an element visible or hidden, whichever is the opposite of what it is already. It's like using hide or show but you don't need to know which one to pick, it performs like the one that will make a difference.

The toggleClass method does something similar to an element's class. If the element already has the class you name, it will remove it. And if it does not have it, it will add it. So it's basically like an automatic combination of addClass and removeClass.

For further info, sample code, and demos, see the jQuery documentation for toggle and toggleClass.