Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to attach an event listener to the DOM, depending upon the screen size

for eg:document.body.addEventListener('wheel', foo, {passive: true}); This should be dynamically added/removed if the screen size is above 500px

like image 793
heyayush Avatar asked Dec 23 '22 14:12

heyayush


2 Answers

As @Rounin says, window.matchMedia is the equivalent of CSS @media queries. But the coolest part is not just that you can check with .matches -- the awesome thing is that you can add an event-listener that gets fired when the state changes.

You want something to happen when the screen width transition to above or below 500px -- you want to add a mouse wheel listener when the screen is >500px and remove it when the screen is <500px

You will also have to check for .matches initially to decide whether to add the listener or not when your page first loads, as @Rounin shows, but then the listener can be added and removed automatically based on matching the media query.

let widthMatch = window.matchMedia("(min-width: 500px)");
// mm in the function arg is the matchMedia object, passed back into the function
widthMatch.addEventListener('change', function(mm) {
    if (mm.matches) {
        // it matches the media query: that is, min-width is >= 500px
        document.body.addEventListener( etc. );
    }
    else {
        // it no longer matches the media query
        // remove the event listener
    }
});
like image 104
Stephen P Avatar answered Dec 28 '22 09:12

Stephen P


how to attach an event listener to the DOM [...] only if the screen size is above 500px

window.matchMedia is the javascript equivalent of CSS @media queries.

For example, the following code verifies that the screen width is above 500px.

var widerScreenWidth = window.matchMedia("(min-width: 501px)");

if (widerScreenWidth.matches) {

    // [... YOUR CODE HERE...]

}
like image 34
Rounin - Glory to UKRAINE Avatar answered Dec 28 '22 11:12

Rounin - Glory to UKRAINE