-1

I've a landing page with twenty images positioned in simple grid. When viewport is larger than 992px must be hover jQuery event on every single image and when viewport is lower than 992px must be click jQuery event to display another image. I've read several questions that deal with the same problem. I set this way:

  if( w < 992){

  $('#01').on('click', function(){
    $('#riv-01').fadeIn('fast');
    $('.overlay').fadeIn('fast');
  });

  ...

  }else{

   $('#01').hover(
  function() {
    $('#riv-01').fadeIn('fast');
  },function() {
    $('#riv-01').fadeOut('fast');
  }
);

  }

but when browser window is resized and, for example, from greater than 992 become less than 992, hover effect is executed.

I get viewport width with:

  var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

and to update w when the resize event occurs:

 var resizeId;


  function resizingDone() {
   w = Math.max(document.documentElement.clientWidth, window.innerWidth ||     0);
   console.log(w);
  }

  $(window).resize(function() {
   clearTimeout(resizeId);
   resizeId = setTimeout(resizingDone, 500);
  });

Where am I wrong?

Thanks

FilippoLcr
  • 109
  • 1
  • 9
  • Once you execute `$(...).hover(...)` or `$(...).click(...)` that listener will always be called until you [remove it](http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery). – nem035 Aug 26 '16 at 12:39

1 Answers1

0

You should disconnect your events when the window is resized.

var resizeId;

 function resizingDone() {
   w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
   console.log(w);
   if (w < 992) {
     $('#01').on('click', function() {
       console.log('click');
     });
     $('#01').off('hover');
   } else {
     $('#01').off('click');
     $('#01').hover(function() {
       console.log('hover');
     });
   }
 }

 $(window).resize(function() {
   clearTimeout(resizeId);
   resizeId = setTimeout(resizingDone, 500);
 });

 resizingDone();

https://jsfiddle.net/Loy9cLcm/

Jquery documentation for : .off()

Quentin Roger
  • 5,985
  • 2
  • 21
  • 35