for eg:document.body.addEventListener('wheel', foo, {passive: true});
This should be dynamically added/removed if the screen size is above 500px
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
}
});
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...]
}
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