Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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
    }
});

Solution 2:

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...]

}

Solution 3:

you have 3 options:

  1. check the window size on load and add the listener if > 500: easiest solution but will not adjust if the user resizes the window.
  2. add a listener to window resize and every time the width changes add or remove the 'wheel' event listener depending on the width.

  3. always add an event listener to 'wheel', but inside the event callback, check for the width every time the callback runs before executing your logic


Solution 4:

function getScreenWidth() {
  var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0]

  return w.innerWidth || e.clientWidth || g.clientWidth
}

function wheelListener() {
  console.log(getScreenWidth())
}

window.onresize = function() {
  if (getScreenWidth() > 500) {
    document.body.addEventListener('wheel', wheelListener, {passive: true})
  } else {
    document.body.removeEventListener('wheel', wheelListener)
  }
}

// to apply when the window loaded
window.onresize()

Post a Comment for "How To Attach An Event Listener To The DOM, Depending Upon The Screen Size"