0

I have the following jQuery code.

$(".item").hover(function(){
  $(this).find('.item-hover').css("display","block");
  }, function(){
  $(this).find('.item-hover').css("display","none");
});

I want this jQuery code to work only if the screen size is bigger than 768.

I tried the following method but it didn't helped me.

 $(window).resize(function() {
   if ($(this).width() >= 768) {
    $(".item").hover(function(){
      $(this).find('.item-hover').css("display","block");
      }, function(){
      $(this).find('.item-hover').css("display","none");
    });
  }
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Soonang Rai
  • 41
  • 1
  • 8

1 Answers1

3

Currently, you are attaching your mouseenter/mouseleave handlers every time the window is resized, you don't want to do that.

You need only check the width of the window when the mouseenter event handler itself is invoked.

Another note: use window.matchMedia() rather than checking $(window).width(), as the latter cannot always be relied on:

$(".item").hover(function(){
    if(window.matchMedia('(min-width: 768px)').matches){
        $(this).find('.item-hover').css("display","block");
    }
}, function(){
    $(this).find('.item-hover').css("display","none");
});

Having said that, as already highlighted, (assuming you don't need it for functionality not described here) you needn't use JavaScript at all for this. A little CSS alone will do the job:

.item .item-hover{
    display: none;
}

@media (min-width: 768px){
    .item:hover .item-hover{
        display: block;
    }
}
George
  • 36,413
  • 9
  • 66
  • 103