Turning off .hover() if window size changes

Viewed 23

I would like to turn off a jQuery .hover() function if the window size changes to less than 300px. I wrote this code:

$(window).on("resize", function() {
  if ($(window).width() > 300) {
    $(".link").hover(function() {
      $(this).text("Alternative Text");
    }, function() {
      $(this).text("Hover me");
    });
  } else {
    $('.link').off("hover");
  }
}).resize();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="link">Hover me</div>

If I change my window size to less than 300px and then reload the page, it works perfectly like expected. The else function is not even needed in this case. But if the window size gets manually changed by the user to less to 300px, the hover function just stays.

How can the hover function be removed for window sizes under 300px?

1 Answers

Since hover is an hybrid event, I don't think it can be revoked. Here's a workaround: use a global variable (or check $(window).width() every hover).

var is_desktop = $(window).width() > 300;
$(window).on("resize", function() {
  if ($(window).width() > 300) {
    is_desktop = true
  } else {
    is_desktop = false
  }
})


$(".link").hover(function() {
  if (is_desktop) {
    $(this).text("Alternative Text");
  }
}, function() {
  if (is_desktop) {
    $(this).text("Hover me");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="link">Hover me</div>

If you do want to remove the handlers, then define mouseenter and mouseleave using 2 functions that can then be referenced in the off for those events.

Related