Easily run JS function only if on desktop (Bootstrap example)
HTML
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">One more separated link</a></li>
</ul>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
<div class="starter-template">
<h1>Run JavaScript function only if NOT on mobile</h1>
<p class="lead">In this case, I'm only checking if the navbar toggle is visible or not to decide whether to run the function. So, you just let the CSS handle the screen sizes. Much easier!</p>
<p>In this example, the menu dropdown only activates on hover if the navbar toggle is not visible. The page has to be refreshed after you've changed the viewport size in order to display properly but this won't be a problem if you're truly on a mobile browser.</p>
</div>
</div><!-- /.container -->
CSS
body {
padding-top: 50px;
}
JAVASCRIPT
// If NOT on mobile do the following:
//-----------------------------------------------
$(document).ready(function() {
// run test on initial page load
checkSize();
// run test on resize of the window
$(window).resize(checkSize);
});
//Function to the css rule
function checkSize(){
if ($(".navbar-toggle").css("display") == "none" ){
$(".dropdown").hover(
function() {
$('.dropdown-menu', this).stop( true, true ).fadeIn("fast");
$(this).toggleClass('open');
},
function() {
$('.dropdown-menu', this).stop( true, true ).fadeOut("fast");
$(this).toggleClass('open');
}
);
}
}
//-----------------------------------------------