Javascript - Run my script only if landscape is detected
I'd keep it simple, if screen height is less than width, then the user is in landscape mode. You can grab the height and width from the global window
object.
if (window.innerWidth > window.innerHeight) {
// The user is in landscape mode!
userInLanscapeFunc();
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight
You can solve this using matchMedia
:
const matchesMediaQuery = window.matchMedia('(max-width:999px) and (orientation:landscape)').matches;
if (matchesMediaQuery) {
// do something
}
Make sure to note the browser support in the MDN link.
EDIT TO PROVIDE CONTEXT:
Because the user may be moving around their screen, you will want to make this evaluation inside VerHayMas
, each time it is run, to determine if the main body of the script should be executed:
var clicksVerHayMas = 0;
function VerHayMas() {
var isLandscapeAndMeetsSizeRequirements = window.matchMedia('(max-width:999px) and (orientation:landscape)').matches;
if (isLandscapeAndMeetsSizeRequirements) {
clicksVerHayMas = clicksVerHayMas + 1;
if (clicksVerHayMas == 1) {
document.getElementById('mas-menu').style.display = 'block';
window.setTimeout(function() {
$('#mas-menu').fadeOut('slow');
}, 4000);
}
}
};
So VerHayMas
will be run on every click, but only if the screen meets the requirements as determined by the media query string will it execute the code inside the if
block.