Question

I am not sure how to do this since I am a newbie. I need a dropwdown menu .dmenu when clicked a button .dropB and need that .dmenu to hide as soon as the button is cliked or clicked anywhere outside the button.

$('.dropB').click(function(){
      $('.dmenu').toggle();
})

But this does not allows it to hide when clicked anywhere outside the .dropB. Please any help would be appreciated.

Was it helpful?

Solution

You can use:

$('.dropB').click(function (e) {
    e.stopPropagation();
    $('.dmenu').toggle();
})

$(document).click(function (e) {
    if (!$(e.target).is('.dmenu')) {
        $('.dmenu').hide();
    }
})

Fiddle Demo

OTHER TIPS

Use delegation to handle clicks on document. Check the target, if it matches your button then toggle the menu. If not, then hide the menu.

Demo: http://jsfiddle.net/abhitalks/ztxa2/

$(document).on("click", function(e) {
    var $target = $(e.target);
    if ($target.hasClass("dropB")) {
        $('.dmenu').toggle();
    } else {
        if (! $target.hasClass("dmenu")) {
            $('.dmenu').hide();
        }
    }
})

You may also want to check if the target is the menu itself, so as not to hide itself when clicked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top