Reputation: 308
I have some JavaScript that I only want to run if the screen size is more than 900px. So I have this:
if (document.documentElement.clientWidth > 900) {
$('.menu-item-2477').hover(
function () {
$('.menu-item-2477 ul').css({
display: 'block'
});
$('.menu-item-2477 ul').animate({
height: '100px'
}, 200);
},
function () {
$('.menu-item-2477 ul').animate({
height: '0px',
}, 200, function () {
$('.menu-item-2477 ul').css({
display: 'none'
});
});
});
}
This works fine when you load the page, but if you change the window size, it ignores the if statement. I know that I should do some sort of resize function, like wrap the whole thing in
$(window).resize(function(){ }
but that didn't work when I tried it. So what can I do to make this work after resizing the window?
Upvotes: 0
Views: 136
Reputation: 581
Wrapping it in $(window).resize(function(){})
won't work, as you'd be binding the handlers multiple times on hover.
What you could do is move the document.documentElement.clientWidth > 900
logic to inside the hover
handlers. So it'd look more like
$('.menu-item-2477').hover(
//Hover in function
function(){
if (document.documentElement.clientWidth > 900) {
...
}
},
//Hover out function
function(){
if (document.documentElement.clientWidth > 900) {
...
}
}
});
This way it will check the window size on every event, and perform different logic based on that. Nothing will happen on the resize of the window, as it checks only when it needs to know.
Upvotes: 5