3

I write such function which on screen with width > 1200 have hover effect and show menu

$(window).resize(function(){
    var width = $(window).innerWidth();
    dropDown(width);
});

var dropDown = function(width){
    if(width > 1200){
        $(".dropdown").hover(function() {
                $('.dropdown-menu', this).stop( true, true ).fadeIn("fast");
                $(this).toggleClass('open');
                $('b', this).toggleClass("caret caret-up");
            }, function() {
                $('.dropdown-menu', this).stop( true, true ).fadeOut("fast");
                $(this).toggleClass('open');
                $('b', this).toggleClass("caret caret-up");
            }
        );
    }
};

The problem is when i refresh page on mobile size - all looks fine, but then change size of window > 1200px and then change size of window < 1200px my dropDown show when i hover, but i don't need it, it must open only when i click. Where is the problem? What i should do?

My html

<li class="dropdown">
    <a href="" class="dropdown-toggle" data-toggle="dropdown">DROPDOWN <b class="caret"></b></a>
      <ul class="dropdown-menu">
         <li><a href="#">1</a></li>
         <li><a href="#">2</a></li>
      </ul>
</li>
  • 2
    You'll be better of using [media queries](http://stackoverflow.com/a/18477316/542251) rather than javascript. (Providing your targeting [browsers that support media queries](http://caniuse.com/#feat=css-media-resolution)) – Liam Mar 15 '16 at 09:49

1 Answers1

5

You've not removed the hover handler when the window is less that 1200 wide, so the event handler still exists and works. The else part of the if statement below will fix that for you...

var openDropDown = function(el) {
    var $el = $(el);
    $('.dropdown-menu', $el).stop( true, true ).fadeIn("fast");
    $el.toggleClass('open');
    $('b', $el).toggleClass("caret caret-up");
};
var closeDropDown = function(el) {
    var $el = $(el);
    $('.dropdown-menu', $el).stop( true, true ).fadeOut("fast");
    $el.toggleClass('open');
    $('b', $el).toggleClass("caret caret-up");
};

var dropDown = function(width){
    if(width > 1200){
        $(".dropdown")
            .off("click")
            .hover(function() {
                openDropDown(this);
            }, function() {
                closeDropDown(this);
            });
    }
    else {
        $(".dropdown")
            .off("mouseenter mouseleave")
            .on("click", function() {
                if ($(this).hasClass("open")) {
                    closeDropDown(this);
                }
                else {
                    openDropDown(this);
                }
            });
    }
};

I've also moved the code to open and close the dropdown into separate functions so that it can be reused. I then added a click handler to make the dropdown work when clicked when the window is < 1200 wide.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67