简体   繁体   中英

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

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

Assume if you are writing a function name exampleNotForMobileDevicese() if the window width is less than 768 then the next code wont excute beacuse we have use return ie if the condition satisfies then the execution will stop

 function exampleNotForMobileDevicese(){ if(window.innerwidth < 768){ return } your business logics....... } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM