Zach Nicodemous
Zach Nicodemous

Reputation: 9487

jQuery Toggle Issue

I am having an issue with a jQuery toggle - you can see the issue here: http://jsfiddle.net/tKUgg/3/

As you can see, each item that appears in the yellow box, also appears in the black box. When you click "Main Item" in the black box, the corrosponding item in the yellow box is toggled.

The problem I am having is that when one of the sub-items is clicked, instead of toggling only itself, it also toggles its parent. I need it to only toggle itself. (For example, if you click "Sub Item a" in the black box, it should only toggle "Sub Item a" in the yellow box, but at the moment it toggles both "Sub Item a" and the parent "Main Item")

I am fairly new to jQuery so I am sure its a stupid mistake. How can I fix this?

(Note: The code is designed to work with a content management system so new map layers (categories) can be added/removed dynamically and have a corrosponding item appear in the menu with a toggle. Thats why its a little "spaghetti" as some of you have pointed out)

Thanks

Zach

Upvotes: 0

Views: 218

Answers (2)

John Strickler
John Strickler

Reputation: 25421

You may want to consider revising the spaghetti code you have going on. My brain exploded when I looked at it.

Mentioned by DNR - stopPropagation() is necessary here when dealing with nested lists.

http://jsfiddle.net/V7CPr/

Upvotes: 0

DNR
DNR

Reputation: 986

Each sub-item is a child element of the main item. So, when you're clicking on the sub-item, you're ALSO clicking on the main item - which is why it also toggles.

To prevent this - you must call:

e.stopPropagation();

on the click event that's passed into your jQuery click handler.

Learn about that here.

Upvotes: 1

Related Questions