Reputation: 147
So basically I've googled and done research on how to do this, but haven't managed to make it work.. I've declared a variable called width. I want my JS to check, if the width of the screen is smaller than 660px, then width shall be 140px, else it should be 100px. The variable, width, should only change when I'm rotating the device "phone", but it isn't working? I want the variable should check the width of the screen whenever i rotate the device. I've worked on it for a long time but couldn't solve it. I know of media queries, but I would like to change the variable in JS for other reasons..
JS
var width = 0;
function check()
{
if (window.innerWidth < 660)
{
width = 140;
}
else{
width = 100;
}
}
window.addEventListener("orientationEvent", check);
document.write(width);
Upvotes: 1
Views: 506
Reputation: 24130
I would suggest you to look into window.matchMedia and MediaQueryList.
But be aware that these are latest and experimental feature and may not be supported by all the browsers.
var mediaQueryList = window.matchMedia("(orientation: portrait)");
// Create the query list.
function handleOrientationChange(mql) { ... }
// Define a callback function for the event listener.
mediaQueryList.addListener(handleOrientationChange);
// Add the callback function as a listener to the query list.
handleOrientationChange(); // Run the orientation change handler once.
function handleOrientationChange(evt) {
if (evt.matches) {
/* The viewport is currently in portrait orientation */
} else {
/* The viewport is currently in landscape orientation */
}
}
Now next thing is call changeWidth method when viewport changes.
var width = 0;
function changeWidth() {
if (window.matchMedia("(min-width: 600px)").matches) {
/* the viewport is at least 600 pixels wide */
width = 140;
} else {
/* the viewport is less than 600 pixels wide */
width = 100;
}
}
More documentation related information here.
Upvotes: 1
Reputation: 2854
Actually you should list orientationchange MDN
var width = 0;
function check(){
if (window.innerWidth < 660) {
width = 140;
} else {
width = 100;
}
// Just for demo
document.querySelector('body').innerHTML = width;
}
window.addEventListener("orientationchange", check);
Upvotes: 1
Reputation: 859
The event is called deviceorientation
so your code will be:
window.addEventListener('deviceorientation', check);
Remember that events in javascript are all lowercase.
Upvotes: 1