Reputation: 159
I have the following code:
$(document).ready(function(){
var widwith = $(window).width();
if(widwith < 1150) {
$('.menu-item-has-children').click(function(){
$('.sub-menu').toggleClass('sub-display');
});
}else if(widwith > 1150) {
$('.menu-item-has-children').hover(function(){
$('.sub-menu').toggleClass('sub-display');
});
}
});
it detects the window width, and depending on the width makes a sub menu apear on either click (on mobile) or hover on desktop. The issue I am having is if you resize the window I need ot re-run the if statement in case is crosses over the threshold of 1150px wide... but I have no idea how I would do this? any idea?
Upvotes: 0
Views: 371
Reputation: 39248
jQuery(document).ready(function(){
jQuery( window ).resize(function() {
resize();
});
resize();
});
function resize()
{
var widwith = jQuery(window).width();
if(widwith < 1150) {
jQuery('.menu-item-has-children').click(function(){
jQuery('.sub-menu').toggleClass('sub-display');
});
}else if(widwith > 1150) {
jQuery'.menu-item-has-children').hover(function(){
jQuery('.sub-menu').toggleClass('sub-display');
});
}
}
Just add a window resize handler.
Upvotes: 1
Reputation: 1873
You're almost there. First you need to pull the core resize event logic into a separate function so you can re-use:
function resize() {
var widwith = $(window).width();
if(widwith < 1150) {
$('.menu-item-has-children').click(function(){
$('.sub-menu').toggleClass('sub-display');
});
}else if(widwith > 1150) {
$('.menu-item-has-children').hover(function(){
$('.sub-menu').toggleClass('sub-display');
});
}
}
Which will make your document on ready listener look like so:
jQuery(document).ready(function() {
resize();
});
Then add an event listener for the resize event:
jQuery(window).resize(function() {
resize();
});
That should do it.
Upvotes: 0
Reputation: 2780
You can use Jquery's resize method
$(window).resize(function() {
// put yout code here
});
Upvotes: 0