Reputation: 3137
I've got a fairly simple navigation menu that opens and closes on click. The menu behaviour only comes into play when the browser viewport is below a certain size.
It all works great 90% of the time. The remaining 10% of the time (when I'm demonstrating it to the client, natch) the click event doesn't fire at all. As far as I can tell, the problem only occurs after the browser has been resized a few times, but as it usually works normally when the window has been resized, it's difficult to track down why it's happening.
Code:
var smallViewport = false;
$(document).ready(function(){
if($(window).width() < 520) {
smallViewport = true;
}
if(smallViewport == true) {
$('nav.main').click(function(){
console.log(' + clicky clicky');
if($(this).find('.level-1').hasClass('open') == true) {
$(this).find('.level-1').slideUp('fast').removeClass('open');
} else {
$(this).find('.level-1').slideDown('fast', function(){ $(this).addClass('open'); });
}
})
}
});
$(window).resize(function() {
if($(window).width() < 520) {
smallViewport = true;
} else {
smallViewport = false;
}
console.log(smallViewport);
if(smallViewport == true) {
$('.level-1').removeClass('open').css('display','none');
} else {
$('.level-1').css('display','block');
}
});
When the problem chooses to manifest itself, console.log(smallViewport) in the resize function outputs 'true' when it should be true, the click event just refuses to fire along with it.
Has anybody encountered a similar problem before? Any obvious solutions I'm missing?
Upvotes: 0
Views: 1680
Reputation: 1596
Put the viewport check inside the click event handler. As it is now, the event handler isn't bound if the check evaluates to false on page load. Try changing it to this:
$('nav.main').click(function(){
if(smallViewport == true) {
console.log(' + clicky clicky');
if($(this).find('.level-1').hasClass('open') == true) {
$(this).find('.level-1').slideUp('fast').removeClass('open');
} else {
$(this).find('.level-1').slideDown('fast', function() {
$(this).addClass('open');
});
}
}
});
Upvotes: 2
Reputation: 293
You're only binding the click when the page loads, not when it's resized
if $(window).width() < 520
evaluates as false on the page load, the click event will not be bound - which is why your console log is correct but the event is not firing
Upvotes: 2