JSFiddle - React, Tailwind, and code Playground

by georgie

HTML

<div id='testOutput'>-</div>

CSS

@media only screen and (orientation:landscape){
    body{
        background-color: blue;
        color: #fff;
    }
    body::before{
       content: '-- via mq: landscape --';
    }
}

@media only screen and (orientation:portrait){
    body{
        background-color: red;
    }
    body::before{
       content: '-- via mq: portrait --';
    }
}

</style>

<meta name='viewport' content='initial-scale=1.0, width=device-width' />
<style>

JavaScript

var viewport = document.createElement("meta");
viewport.setAttribute('name', 'viewport');
viewport.setAttribute('content', 'width=device-width, initial-scale=1');
document.getElementsByTagName('head')[0].appendChild(viewport);


output = document.getElementById('testOutput');
output.innerHTML = '<br>js output<br>' 

var mql_landscape = window.matchMedia("(orientation: landscape)")
var mql_portrait = window.matchMedia("(orientation: portrait)")

var handleOrientationChanged = function (mql) {
    if (mql_landscape.matches && (mql == mql_landscape || !mql)) {
        console.log('enter landscape')
        output.innerHTML += 'enter landscape<br>'
    }
    
    if(mql_portrait.matches && (mql == mql_portrait || !mql)){
        console.log('enter portrait')
        output.innerHTML += 'enter portrait<br>'
    }
}


mql_landscape.addListener(handleOrientationChanged);
mql_portrait.addListener(handleOrientationChanged);
handleOrientationChanged()