Matt Hutch Matt Hutch - 2 months ago 6
jQuery Question

Run JQuery only on small screens

I'm trying to get my jquery to only run when the screen size is mobile. Now of course it's very easy to do this with css but for some reason as soon as I try detecting the screen size with jquery it doesn't work. Anyone know where I'm going wrong here?

<script src="JAVASCRIPT/jquery-3.1.0.min.js"></script>
<script>
if ( $(window).width() > 600) {
}
else {
$(".tbinputArea").focus(function() {
$("#footer").hide();
});

$(".tbinputArea").focusout(function() {
$("#footer").show();
});
}
</script>

Answer

Can you try like this:

var isMobileView = false; //global variable

$(document).ready(function () {

    function setScreenWidthFlag() {
        var newWindowWidth = $(window).width();
        if ( $(window).width() > 600) {   
            isMobileView = false;
        }
        else {
            isMobileView = true;
        }
    }

    $(".tbinputArea").focus(function() {
        if(isMobileView)
            $("#footer").hide();
    });

    $(".tbinputArea").focusout(function() {
        if(isMobileView)
            $("#footer").show();
    });

    setScreenWidthFlag();

    $(window).on("resize", function (e) {
        setScreenWidthFlag();
    });
}); 
Comments