JQuery toggles div children
I have the following HTML code:
<div class="dim"> Menu <div class='hidden'>submenu1</div> <div class='hidden'>submenu2</div> </div> <div class="dim"> Menu2 <div class='hidden'>submenu3</div> <div class='hidden'>submenu4</div> </div> class hidden has display:none
I am trying to make the switch work when I click on a word menu or menu
$('.dim').click(function(){ $('.hidden', this).toggle(); // p00f }); Fiddle: http://jsfiddle.net/maniator/V4X4t/
Update
Checks for the presence of a dim element:
$('.dim').click(function(event){ var isDim = $(event.target).is('.dim'); if(isDim){ //make sure I am a dim element $('.hidden', this).toggle(); // p00f } }); $('.dim').on('click', function () { //$(this).children('.hidden').toggleClass('.hidden');//as-per AndreasAL suggestion $(this).children('.hidden').toggle(); }); $('.hidden').on('click', function (event) { event.stopPropagation(); }); Here is a demo: http://jsfiddle.net/76uTr/
This shows / hides .hidden elements when clicking on a .dim element, but also allows you to click on a .hidden element and not toggle its visibility.
Note that I used .children() instead of .find() , which will select only the 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 insert elements and prevent event bubbles and fire several 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 considered the direct parent of the .dim elements.
Just attach a click event handler and check if the current item has been clicked:
$('.dim').click(function(e) { if (e.target == this) { $(this).children().toggle(); } }); Here's the fiddle: http://jsfiddle.net/V4X4t/6/
Creating bindings in menus and menus 2
<div class="dim"> <a href="#" >Menu</a> <div class='hidden'>submenu1</div> <div class='hidden'>submenu2</div> </div> <div class="dim"> <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" ); }); If you click on any communication submenu that belongs to it, it appears or disappears.
Live demo: http://jsfiddle.net/ZxwpJ/