How do I apply jquery for mobile only?

痞子三分冷 提交于 2020-01-22 15:39:14

问题


I need to apply the following jquery for mobile browsers only:

<script>
   $('.right').insertBefore('left');
</script>

This is to reorder the position of bootstrap columns.

How do I do this? Does it need to be wrapped in something?


回答1:


It always very hard to detect whether its a mobile device's browser or a laptop with a touch screen. So instead of detecting that if you are concern about the screen size then i will recommend you to detect the screen size and if its below certain level(lets say below 481px) then we will assume that its a mobile screen and will execute your needed code as follows:

$(document).ready(function () {
    $(window).on("resize", function (e) {
        checkScreenSize();
    });

    checkScreenSize();

    function checkScreenSize(){
        var newWindowWidth = $(window).width();
        if (newWindowWidth < 481) {
            $('.right').insertBefore('.left');
        }
        else
        {
            $('.left').insertBefore('.right');
        }
    }
});



回答2:


To write jQuery that only applies for mobile devices, just use the sample below and it worked for me.

if(window.outerWidth > 425) {
  alert('your jquery code here - it fires for mobile device only');
}


来源:https://stackoverflow.com/questions/37831945/how-do-i-apply-jquery-for-mobile-only

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!