How to connect an event listener to the DOM, depending on the screen size

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

+4
source share
4 answers

As @Rounin says, window.matchMediais the equivalent of CSS @media queries. But the coolest part is not only what you can check with .matches- it's amazing that you can add an event listener that fires when the state changes.

, - , 500 - , > 500 , , < 500px

.matches, , , , @Rounin, -.

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

DOM [...], 500px

window.matchMedia - javascript CSS @media.

, , 500px.

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

if (widerScreenWidth.matches) {

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

}
+2

3 :

  • , > 500: , , .
  • , 'wheel' .

  • 'wheel', ,

+2
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()
+1

Source: https://habr.com/ru/post/1684695/


All Articles