You can use:
$('.dropB').click(function (e) {
e.stopPropagation();
$('.dmenu').toggle();
})
$(document).click(function (e) {
if (!$(e.target).is('.dmenu')) {
$('.dmenu').hide();
}
})
Frage
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.
Lösung
You can use:
$('.dropB').click(function (e) {
e.stopPropagation();
$('.dmenu').toggle();
})
$(document).click(function (e) {
if (!$(e.target).is('.dmenu')) {
$('.dmenu').hide();
}
})
Andere Tipps
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.