50dollanote
50dollanote

Reputation: 189

jQuery - Drop down show/hide onclick - need to hide when clicking outside

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: 13566

Answers (2)

Abhay Maurya
Abhay Maurya

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

Sridhar R
Sridhar R

Reputation: 20408

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();
    });
});

DEMO

Upvotes: 1

Related Questions