Question

I am trying to enable a jQuery function only if the screen width is above 960px but my code stops working completely when I use the window resize function. I am suspecting that the code is faulty.

So my question is, how do I enable jQuery function only if the width is 960px or wider? I will try to explain better if you don't understand!

Thanks in advance!

jQuery

function window_resize(){
if($(window).width() > 960){
    $('li#portfolio').on('mouseenter', function() {
    $(this).find('#subNav').addClass('active').hide().stop(true,true).fadeIn(300);
    }).on('mouseleave', function() {
    $(this).find('#subNav').stop(true,true).fadeOut(300);
});
}
Was it helpful?

Solution

If you check the window size inside the event handler it will be easy.

    $('li#portfolio').on('mouseenter', function () {
        if ($(window).width() > 960) {
            $(this).find('#subNav').addClass('active').hide().stop(true, true).fadeIn(300);
        }
    }).on('mouseleave', function () {
        if ($(window).width() > 960) {
            $(this).find('#subNav').stop(true, true).fadeOut(300);
        }
    });

OTHER TIPS

You need to combine it with a window resize event:

$(window).resize(function() {
  console.log($(window).width());
  if ($(window).width() < 960) {
     console.log('Less than 960');
  }
  else {
     console.log('More than 960');
  }
});

Try in Fiddle

Add this to your code:

$(function()
{
    $( window ).resize(function(window_resize()) {})          
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top