Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable a script when on mobile device

I have a site which has a parallax scroll effect and it's running the skrollr.js script. It's a mobile first website, but I would like for the script to not run on mobile devices because it won't allow scrolling. Does anyone know how I can prevent the script from running when on a mobile device? Thanks.

The code where the script is uploaded is at then end of the body section. If any other code is needed let me know.

<!-- SCRIPTS -->

<script type="text/javascript" src="js/skrollr.js"></script>
<script type="text/javascript">
    skrollr.init();
</script>

<!--/ SCRIPTS -->
like image 987
Veech Avatar asked Dec 18 '14 19:12

Veech


People also ask

Should I disable JavaScript on my phone?

Although the point of JavaScript is to improve user experience on websites, it does have some downsides. Website owners use JavaScript to show ads and enable ad tracking. By disabling JavaScript, you can avoid these annoyances while maintaining some of your privacy.


1 Answers

You can use modernizr's touch detection in order to check if it's a touch device, and, if yes, don't init the script.

if (Modernizr.touch) {

}
else 
{
    skrollr.init();
}

or you can check for the user agent (this might not be your best option as user agent isn't always reliable), and write a simple if else, with the skrollr init in the else

  var isMobile = {
            Android: function () {
                return navigator.userAgent.match(/Android/i);
            },
            BlackBerry: function () {
                return navigator.userAgent.match(/BlackBerry/i);
            },
            iOS: function () {
                return navigator.userAgent.match(/iPhone|iPad|iPod/i);
            },
            Opera: function () {
                return navigator.userAgent.match(/Opera Mini/i);
            },
            Windows: function () {
                return navigator.userAgent.match(/IEMobile/i);
            },
            any: function () {
                return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
            }
        };

        if (isMobile.any()) {

        }
        else {

             skrollr.init(); 
        }

Another way of testing would be by checking window.innerWidth and only init your script if the screen size is larger than 760px:

if (window.innerWidth > 760) {
skrollr.init();
}
like image 138
baao Avatar answered Sep 20 '22 03:09

baao