user934902 user934902 - 4 months ago 11
jQuery Question

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();
});
}

Answer

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.
}