Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle class on orientation change in javascript

How can we toggle class of an element based on orientation of device.

Example:

<div class="landscape"></div>
@media (orientation: portrait) {
.landscape: {...}
}

I can change landscape css properties. but I want to avoid this.

Instead, I would like to change the class itself thus, it would look like

<div class="portrait"></div> // if orientation is portrait
<div class="landscape"></div> // if orientation is landscape

Any suggestions for this!

Note: Would accept answer for vue as well

Update: screen.orientation doesn't work on safari. solution should work on safari too.

thanks for your appretiatable answers.

like image 214
Radical Edward Avatar asked Aug 21 '20 12:08

Radical Edward


People also ask

How do I change orientation mode?

Select the Start button, then type settings. Select Settings > System > Display, and choose a screen orientation from the drop-down list next to Display orientation.

How do I force Javascript to landscape?

screen. orientation. lock('landscape'); Will force it to change to and stay in landscape mode.

How do I get orientation in Javascript?

Detecting Orientation Changes in Javascript Should you need to simply detect when a user changes orientation, you can use the following event listener: screen. orientation. addEventListener("change", function(e) { // Do something on change });

What is CSS orientation?

The orientation CSS media feature can be used to test the orientation of the viewport (or the page box, for paged media). Note: This feature does not correspond to device orientation.


1 Answers

Check out this code using matchMedia. But maybe I made a mistake somewhere in this code. But the essence and structure are correct.

window.matchMedia('(orientation: portrait)').addListener(function(m) {
       let div_class = document.querySelector('.landscape');
       if (m.matches) {
                div_class.className = 'portrait';
            } else {
                div_class.className = 'landscape';
            }
    });
like image 59
s.kuznetsov Avatar answered Sep 30 '22 05:09

s.kuznetsov