user934902
user934902

Reputation: 1204

Executing different jQuery on browser size (hover vs click)

In my main nav I have a series of submenus. My issue is that on regular browser size I need the menu to open on a hover and on a mobile view I need it to open on a click. I have jQuery that works however I cant turn off the hover on mobile and the click on regular view

HTML

  <ul class="mainMenu">
     <li>
       ITEM
       <ul class="subMenu">
          <li></li>
       </ul>
      </li>
    </ul>

jQuery (code works but cant turn off on mobile/regular view)

$(document).ready(function () {
  $('.mainMenu li').hover(function () {
    $(this).find('.subMenu').stop().fadeIn();
  }, function () {
    $(this).find('.subMenu').stop().fadeOut();
  });

  $('.mainMenu li').click(function () {
    $(this).find('.subMenu').stop().slideToggle();
  });
});

** ALSO TRIED ** (targeting browser size, code doesnt work anymore)

var $browserWidth = window.innerWidth || document.documentElement.clientWidth;
    if ($browserWidth > 768) {
      $('.mainMenu li').hover(function () {
    $(this).find('.subMenu').stop().fadeIn();
  }, function () {
    $(this).find('.subMenu').stop().fadeOut();
  });
    } else if($browserWidth < 768) {
      $('.mainMenu li').click(function () {
    $(this).find('.subMenu').stop().slideToggle();
  });
   }

Upvotes: 1

Views: 675

Answers (2)

user934902
user934902

Reputation: 1204

@Ed Hinchcliffe got me on the right track... this is the answer that ended up working

$(document).ready(function () {
    menuStuff();
});

$(window).resize(function () {
    menuStuff();
});

function menuStuff() {
    var $browserWidth = window.innerWidth || document.documentElement.clientWidth;
    if ($browserWidth > 768) {
        $('.mainMenu > li').unbind().bind({
            mouseenter: function (e) {
                $(this).find('.subMenu').stop().fadeIn();
            },
            mouseleave: function (e) {
                $(this).find('.subMenu').stop().fadeOut();
            }
        })
    } else {
        $('.mainMenu > li').unbind().click(function () {
            $(this).find('.subMenu').stop().slideToggle();
        });
    }
}

Upvotes: 1

Ed_
Ed_

Reputation: 19098

Check out this link.

It details how you can use media queries in JavaScript.

Basically, there's a matchMedia() function whose matches property will return a boolean when you pass it a css media query.

So in your case:

if(window.matchMedia("(min-width: 768px)").matches){
  //your desktop code
}
else{
  //your mobile code.
}

Upvotes: 3

Related Questions