Reputation: 189
I have a drop down menu working using the code below. It show/hides on click fine but I'm looking to get it to hide when I click outside of the menu also - can anybody assist, brain isn't working today?
$( "li.dropmenu" ).click(function() {
$( this ).toggleClass( 'selected' );
if ( $( this ).hasClass( 'selected' ) ) {
$( '.dropdown' ).show();
} else {
$( '.dropdown' ).hide();
}
});
Upvotes: 0
Views: 13569
Reputation: 12277
Its old question but if anyone else has same problem, it can be resolved using click event. Idea is to leave the particular element using its id or class and make click on body.
$('body').click(function(e){
if($(e.target).attr('class')!=='dropmenu')
$('.dropdown').hide();
});
I hope it helps
Upvotes: 0
Reputation: 20418
Try this
$(document).ready( function(){
$( "li.dropmenu" ).click(function() {
$( this ).toggleClass( 'selected' );
if ( $( this ).hasClass( 'selected' ) ) {
$( '.dropdown' ).show();
} else {
$( '.dropdown' ).hide();
}
});
$(document).click( function(){
$('.dropdown').hide();
});
});
Upvotes: 1