Search code examples
jqueryhtmlresizewindow

jquery window resize function only triggering once instead of at every resize


I am trying to set up a jquery function that checks window width in order for a navigation bar to work properly. What I want to happen is this: If the screen width is larger than 949px, initiate a function that that makes hovering on a .dropdown anchor link open up a dropdown sub menu; if the screen width is less than or equal to that 949px, remove that function so that the .dropdown anchor link must be clicked on in order to open the dropdown sub menu (the dropdown links open by default when clicking them- I think this is a bootstrap component).

I created a few functions based on some similar examples I found on stackoverflow but have found that the function only triggers once the screen width has surpassed 949px, so at smaller widths the .dropdown anchors are still opening submenus via hover which is what I don't want.

var width = $(window).width();
$(window).resize(function(){
  if($(this).width()>949){
    $(".dropdown").hover(function(){
      $(this).addClass("open");
    },
    function(){
      $(this).removeClass("open");
    });
  }
});

How can I improve this function so that the .dropdown hover functionality is added at widths above 949px and removed at 949px and below?


Solution

  • Rather than adding and removing bindings, just establish the event binding and check the size before doing anything:

    $(".dropdown").hover(function() {
        if ($(window).width() > 949) {
            $(this).addClass("open");
        }
    }, function() {
        if ($(window).width() > 949) {
            $(this).removeClass("open");
        }
    });
    

    If you add and remove the event handler, you need to prevent doing it twice (e.g. they resize to 980 and then resize to 1050).

    var hover_added = false;
    
    $(window).resize(function() {
        var width = $(this).width();
        if (width > 949 && !hover_added) {
            $(".dropdown").on({
                mouseenter: function () {
                    $(this).addClass("open");
                },
                mouseleave: function () {
                    $(this).removeClass("open");
                }
            });
            hover_added = true;
        } else if (width <= 949 && hover_added) {
            $(".dropdown").off("mouseenter mouseleave");
            hover_added = false;
        }
    });