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.
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.
screen. orientation. lock('landscape'); Will force it to change to and stay in landscape mode.
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 });
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.
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';
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With