Reputation: 7482
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'm trying to get the toggle to work when I click on the word menu or menu2
Upvotes: 8
Views: 30108
Reputation: 220136
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();
}
});
Here's the fiddle: http://jsfiddle.net/V4X4t/6/
Upvotes: 1
Reputation: 146360
$('.dim').click(function(){
$('.hidden', this).toggle(); // p00f
});
Fiddle: http://jsfiddle.net/maniator/V4X4t/
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
}
});
Fiddle: http://jsfiddle.net/maniator/V4X4t/5/
Upvotes: 13
Reputation: 76003
$('.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.
Upvotes: 4
Reputation: 5042
Create anchors at Menu and Menu2
<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" );
});
When click anyone of link submenu belonging to it will will appear or disappear
Live demo: http://jsfiddle.net/ZxwpJ/
Upvotes: 0