I want to show a text to the users if they are on mobile device and the orientation is portrait.
For detecting mobile device, I am using this script:
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
document.write("mobile");
}else{
document.write("not mobile");
}
and for portrait mode, I am using this CSS:
@media (orientation: portrait) {
.land-msg {display: block;}
}
But I can not combine both to work with each other.
Is thee a way I can make it to check both mobile device and orientation in a single code?
Media screen size won't work as I don't want it to show on desktop browser resize.
Any help appreciated.
CodePudding user response:
I have used the below code to make it work:
if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)){
if(window.innerHeight > window.innerWidth){
jQuery(".land-msg").css("display", "block");
}
}else{}
Thank you.
CodePudding user response:
You can use matchMedia to detect orientation (min/max-width etc)
const isMobile = (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent))
function matchMediaHandler(query) {
if (query.matches) { // If media query matches (portrait)
document.body.style.backgroundColor = "orange"
document.body.innerText = isMobile ? 'Mobile Portrait' : 'Desktop Portrait'
} else {
document.body.style.backgroundColor = "yellowgreen"
document.body.innerText = isMobile ? 'Mobile Landscape' : 'Desktop Landscape'
}
}
// orientation query
const orientation = matchMedia("(orientation: portrait)")
// add listener
orientation.addListener(matchMediaHandler)
// trigger on load
matchMediaHandler(orientation)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
There are pure CSS ways to detect mobile devices in a way which is better than userAvent sniffing. To word it another way: never ever do userAgent sniffing. I promise you're doing it wrong.
/* smartphones, touchscreens */
@media (hover: none) and (pointer: coarse) and (orientation: portrait) {
/* ... */
}
Portions of this was taken from here: https://ferie.medium.com/detect-a-touch-device-with-only-css-9f8e30fa1134