I'm trying to check the screen size with Javascript. My elements will be animated differently depending on the size of the screen.
I think I am not too far from the result but without really fully understanding it.
When I load the page I have a console.log that appears twice regardless of the size of the window.
By reducing the window manually, by dragging the mouse, there is: - 2 console.log('MD') when the size for MD is ok - 1 console.log('SM') when the size for SM is ok
By enlarging the window manually, by dragging the mouse, there is: - 1 console.log('MD') when the size for MD is ok - 1 console.log('SM') when the size for LG is ok - 1 console.log('LG') when the size for LG is ok
But by adjusting the size of the window with the browser icon, my console.log are as I wish.
Would it be possible to have more explanation?
I hope I've made myself clear.
let mqls = [
window.matchMedia('screen and (min-width: 768px) and (max-width: 991px'),
window.matchMedia('screen and (min-width: 992px)')
];
function test(mql){
if( mqls[0].matches ){
console.log('MD')
}
else if( mqls[1].matches ){
console.log('LG')
}
else if( !mqls[0].matches && !mqls[1].matches ){
console.log('SM')
}
}
for ( let i =0; i < mqls.length; i++ ){
test(mqls[i]);
mqls[i].addListener(test);
}
mqlsis an array with two elements, you madefor loopto check screen size, so the console output will be twice according tomqlsarray length .