Last active
May 23, 2021 12:49
-
-
Save hullen/7326597 to your computer and use it in GitHub Desktop.
Detects mobile devices: phones, tablets.
mobileCheck is a lightweight Javascript utils for detecting mobile devices and tablets.
Its using User Agent string. Usage:
if ( mobileCheck.smarphone ) { // Code
}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mobileCheck = { | |
ios: (function(){ | |
return navigator.userAgent.match(/iPhone|iPad|iPod/i); | |
}()), | |
android: (function(){ | |
return navigator.userAgent.match(/Android/i); | |
}()), | |
blackBerry: (function(){ | |
return navigator.userAgent.match(/BB10|Tablet|Mobile/i); | |
}()), | |
windows: (function(){ | |
return navigator.userAgent.match(/IEMobile/i); | |
}()), | |
smartphone: (function(){ | |
return (window.innerWidth <= 384 && window.innerHeight <= 640); | |
}()), | |
tablet: (function(){ | |
return (navigator.userAgent.match(/Tablet|iPad|iPod/i) && window.innerWidth <= 1280 && window.innerHeight <= 800); | |
}()), | |
all: (function(){ | |
return navigator.userAgent.match(/Android|BlackBerry|Tablet|Mobile|iPhone|iPad|iPod|Opera Mini|IEMobile/i); | |
}()) | |
}; |
I guess you have done wrong for tablet
tablet: (function(){
return (navigator.userAgent.match(/Tablet|iPad|iPod/i) && window.innerWidth <= 1280 && window.innerHeight <= 800);
}()),
Instead It should be
tablet: (function(){
return (navigator.userAgent.match(/Tablet|iPad|iPod/i) && window.innerWidth <= 1280 && window.innerHeight >= 800);
}()),
One check that I liked was the return (window.innerWidth <= 384 && window.innerHeight <= 640);
for smartphone, but user can resize their window and it would return true
.
One fix is to use:
return (screen.availWidth <= 384 && screen.availHeight <= 640)
or return (screen.width <= 384 && screen.height <= 640)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fiz um teste com algumas variações do seu codigo: http://jsperf.com/mobile-simple-detection