I have the following HTML code:
<div> Menu <div class='hidden'>submenu1</div> <div class='hidden'>submenu2</div> </div> <div> Menu2 <div class='hidden'>submenu3</div> <div class='hidden'>submenu4</div> </div> class hidden has display:none
I'm trying to get the toggle to work when I click on the word menu or menu2
5 Answers
$('.dim').click(function(){ $('.hidden', this).toggle(); // p00f }); Update
Checks for dim element being clicked:
$('.dim').click(function(event){ var isDim = $(event.target).is('.dim'); if(isDim){ //make sure I am a dim element $('.hidden', this).toggle(); // p00f } }); 10$('.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(); }); 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 the .parent element is assumed to be the direct parent of the .dim elements.
Simply attach a click event handler, and check if the current element is the one that was clicked:
$('.dim').click(function(e) { if (e.target == this) { $(this).children().toggle(); } }); take a look at this tutorial which may give you an idea
Create anchors at Menu and Menu2
<div> <a href="#" >Menu</a> <div class='hidden'>submenu1</div> <div class='hidden'>submenu2</div> </div> <div> <a href="#" >Menu2</a> <div class='hidden'>submenu3</div> <div class='hidden'>submenu4</div> </div> and script:
$(".dim > a").click( function ( e ){ e.preventDefault() // prevent default action - hash doesn't appear in url $( this ).parent().find( "div" ).toggleClass( "hidden" ); }); When click anyone of link submenu belonging to it will will appear or disappear