简体   繁体   中英

Responsive jQuery doesn't work: Click below 768px width and hover above 768px

I need a menu to open when I am hovering over an li when above 768px window width, and it to open when I click the same li when below 768px window width. I keep having problems where the click, or hover, carries over between the two screen sizes (0-768px and 769 and up).

function colorChangeTest(width){
   if (width <= 767) {
      $('li').click(function() {
         $(this).toggleClass('colorChange');
      });
   } else {
      $('li').hover(function() {
         $(this).toggleClass('colorChange');
      });
   }
}

$(function () {
   var onLoadWidth = $(window).width();
   colorChangeTest(onLoadWidth);
   $(window).resize(function () {
      var resizeWidth = $(window).width();
      colorChangeTest(resizeWidth);
   });
})

jsfiddle example

What is the best way to do responsive jQuery that tell something it can be clicked, or hovered, depending on screen size, and determine this on page load and window resize?

FYI it is better to attach the same event listeners once in code to the same elements. In your case each time when window is resizing new event listeners (hover or click) are attached again and again.

Use unbind to aviod it. For example:

function colorChangeTest(width){
   var $li= $('li');
   $li.unbind();
   if (width <= 767) {
      $li.click(function() {
         $(this).toggleClass('colorChange');
      });
   } else {
      $li.hover(function() {
         $(this).toggleClass('colorChange');
      });
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM