Learn

Similar to other effects methods, you can use a toggle method instead of chaining the .addClass() and .removeClass() methods together.

The .toggleClass() method adds a class if an element does not already have it, and removes it if an element does already have it. Its syntax looks like:

$('.example-class').toggleClass('active');

In the example above:

  • .toggleClass() is called on .example-class elements.
  • .toggleClass() will add the 'active' class to .example-class elements if they do not have it already.
  • .toggleClass() will remove the 'active' class from .example-class elements if they do have it already.

Instructions

1.

In main.js we changed the mouse enter event to a click event so you can see the changes that are caused by the .toggleClass() method below.

Let’s use .toggleClass() to add or remove the hide class from the navigation menu element.

2.

Use .toggleClass() to add and remove the button-active class from the menu button.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?