I am looking to stop JQuery functions at mobile device widths (768px and below). I have tried using $(window).width() to detect screen width, then use an if statement, but can't seem to get it working.
$(document).ready(function(){
var resolution = $(window).width();
if (resolution >= 768) {
$('.img-1').hover(function(){
$(this).animate({right: "350px"},1000);
$('#desc1').show(1000);
});
$('.img-1').mouseleave(function(){
$(this).animate({right: "0px"},1000);
$('#desc1').hide(1000);
});
} else {
// NO SCRIPT
}
});
Here is a link to a codepen of it: http://codepen.io/SRBET/pen/dOJoJb/
Any help would be much appreciated!
Thanks
Try this:
var resolution = $(window).width();
if (resolution > 768) {
$(document).ready(function(){
$('.img-1').hover(function(){
$(this).animate({right: "350px"},1000);
$('#desc1').show(1000);
});
$('.img-1').mouseleave(function(){
$(this).animate({right: "0px"},1000);
$('#desc1').hide(1000);
});
});
} else {
// NO SCRIPT
}
Use the if condition before ready function. its working in code panel (I have tried it on chrome). Also remove equal sign if you want that it should not work on 768px.
We want to achieve 2 things.
So, how can we achieve this in the most logical way possible?
var resetEvents = function() {
$('.img-1').off()
$('#desc1').off()
checkScreen();
}
var checkScreen = function() {
if ($(window).width() >= 768) {
$('.img-1').hover(function(){
$(this).animate({right: "350px"},1000);
$('#desc1').show(1000);
});
$('.img-1').mouseleave(function(){
$(this).animate({right: "0px"},1000);
$('#desc1').hide(1000);
});
}
}
$(document).ready(function(){
resetEvents();
$(window).resize(function() {
resetEvents()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="img-1">hi, i'm img-1</div>
<div style="display:none;" id="desc1">hi, i'm desc1</div>
(Open in full screen to see the events working, and small screen to see them disabled)
I've wrapped your code inside multiple functions, and call the first one on $(document).ready(). The first function resets all the current event listeners on the elements. Then calls the second function.
In the second function, we check the (new?) width of the window, and apply event listeners if it meets the requirement. At last, we make sure to attach the resetEvents() event to the resize event, so when someone changes orientation on an iPad, he or she can still experience the events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With