Here's my snippet for detecting a mobile display based on the screen size. You can force the site to stay in desktop-mode by adding a forceDesktop param to the URL.
I`m new to jquery so if you have suggestions, please comment.
Credits go to brandonjp: How can I get query string values in JavaScript?
<script>
$.urlParam = function(name, url) {
if (!url) {
url = window.location.href;
}
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
if (!results) {
return undefined;
}
return results[1] || undefined;
}
window.onload = function() {
var forceDesktop = $.urlParam('forceDesktop');
if (!forceDesktop) {
if ( $(window).width() < 639) {
var url = "http://m.mysite.com/";
$(location).attr('href',url);
}
}
};
</script>
In summary, we recommend looking for the string “Mobi” anywhere in the User Agent to detect a mobile device. Like this: if (/Mobi/. test(navigator.
matchMedia() The Window. matchMedia() is one of the best properties for detecting mobile users with JavaScript.
It works by examining information contained in the HTTP headers, particularly User Agent strings sent by all web-enabled devices. The User Agent is looked up in a database that returns any requested information including device type.
You can use JavaScript window. matchMedia() method to detect a mobile device based on the CSS media query. You may also use navigator. userAgentData.
why not this?
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
window.location = "http://m.mysite.tld/";
}
Actually, I believe that it is important to detect mobile from window width.
So here is the way that I am using.
function detectmob() {
if(window.innerWidth <= 800 || window.innerHeight <= 600) {
return true;
} else {
return false;
}
}
if (detectmob()){
top.location.href="mobile";
}
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