Add/remove class to body depending on device orientation (pure javascript) with change detection
window.onload = function () {
// Find matches
var mql = window.matchMedia("(orientation: portrait)");
// Get body tag
var bodyClass = document.querySelector('body').classList;
// If there are matches, we're in portrait
if(mql.matches) {
document.getElementsByTagName('body')[0].className += ' isPortrait';
// else we're in landscape
} else {
document.getElementsByTagName('body')[0].className += ' isLandscape';
}
// Add a media query change listener
mql.addListener(function(m) {
if(m.matches) {
bodyClass.remove('isLandscape');
bodyClass.add('isPortrait');
}
else {
bodyClass.remove('isPortrait');
bodyClass.add('isLandscape');
}
});
};