I have the following HTML code:
Menu
submenu1
-
$('.dim').on('click', function () {
//$(this).children('.hidden').toggleClass('.hidden');//as-per AndreasAL's suggestion
$(this).children('.hidden').toggle();
});
$('.hidden').on('click', function (event) {
event.stopPropagation();
});
Here is a demo: http://jsfiddle.net/76uTr/
This shows/hides the .hidden
elements when clicking on a .dim
element but it also allows you to click on a .hidden
element and not toggle it's visibility.
Notice that I used .children()
instead of .find()
which will only select direct descendants of the root element (.dim
).
Also note that .on()
is new in jQuery 1.7 and in this case is the same as .bind()
.
UPDATE
Using event.stopPropagation()
we can allow ourselves to nest elements and not let events bubble-up and trigger multiple event handlers:
$('.dim').on('click', function (event) {
event.stopPropagation();
$(this).children('.hidden').toggle();
});
$('.parent').on('click', function () {
$(this).children('.dim').toggle();
});
$('.hidden').on('click', function (event) {
event.stopPropagation();
});
Here is a demo: http://jsfiddle.net/76uTr/1/
Here the .parent
element is assumed to be the direct parent of the .dim
elements.