Reputation: 1151
I've been trying to make it so my nav will hide when the user clicks off. I've only managed to get so far and I'm obviously doing something wrong.
This is what I have so far:
Without body click http://jsfiddle.net/yL45ds8j/
Attempting body click (it just hides it immediately) http://jsfiddle.net/yL45ds8j/1/
Code:
function handler1() {
$('.headnav').addClass('open').animate({
top: "0"
},400);
$(this).addClass('open');
$(this).one("click", handler2);
}
function handler2() {
$('.headnav').removeClass('open').animate({
top: "-100%"
},400);
$('.menuBtn').removeClass('open');
$('.menuBtn').one("click", handler1);
}
$(".menuBtn").one("click", handler1);
$('body').click(function(event) {
if(!$(event.target).closest('.headnav.open').length) {
if($('.headnav').hasClass("open")) {
$('.headnav').removeClass('open').animate({
top: "-100%"
},400);
}
}
});
Does anyone have any suggestions how I could fix this? Many thanks
Upvotes: 0
Views: 258
Reputation: 247
The click event of menuBtn bubbles up to the body, and the handler of body click event closes it. Please stop the propagation of event in the menuBtn handlers.
e.stopPropagation();
Fiddle: http://jsfiddle.net/yL45ds8j/8/
This is much cleaner solution: jsfiddle.net/yL45ds8j/6
Upvotes: 2