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

Trigger toggle function with multiple elements?

I have a secondary menu that reveals when you click "Menu".

You can click "Menu" to hide it again (using a toggleClass function), but I also want the div to hide if the user clicks one of the secondary menu links.

Essentially, I want this: $('#menu-botton' || '#secondary-menu li').click...

I know that isn't proper syntax, but I'm looking for a way to allow the user to trigger the toggle in several different ways—with the button or the secondary menu items.

Can someone point me in the right direction? Thanks!

Would it be possible to see a demo of what you have. Maybe uploaded to jsFiddle or Codepen.

2 Answers

Hi Andrew,

What you're trying to do isn't that far off from what you can do.

jQuery has a multiple selector which lets you specify multiple selectors separated by commas.

In your case it would look something like this:

$('#menu-button, #secondary-menu li').click()

There is also the .add method which creates a new jQuery object and adds on the passed in elements.

That would work like this:

$('#menu-button').add('#secondary-menu li').click()

I think for this situation it's probably simpler to use the multiple selectors.

I created a codepen demo illustrating each way. https://codepen.io/anon/pen/mVOgaE

Post more code if I've misunderstood what you need.

Awesome, thanks! I just realized the easiest way to do it would be to use a class instead, and assign it to multiple elements. I guess I got so used to using id's that I forgot you could use classes with toggles. Doh! But good to know about those alternative methods too.

I thought about that after posting but to me it didn't seem easier. It requires more work on the html side. Presumably you have several of those secondary list items so you're having to add a class attribute to multiple elements in the html vs. adding one more selector in the jQuery.

Also, if you have to update the menu in the future and add another item you have to remember to add the class as well or it won't work for that particular item. With the multiple selectors you wouldn't have to worry about it.