Javascript matchMedia not working on browser resize

30 views Asked by At

I am using matchMedia in Javascript to fire the function called myFunction when the window is equal or bigger than 1200px and is not a touch device. The function works when the document loads but not on browser resize.

When the window is smaller than 1200px, I would like to stop firing the function.

The JS:

function isTouchDevice() {
  return (('ontouchstart' in window) ||
      (navigator.maxTouchPoints > 0) ||
      (navigator.msMaxTouchPoints > 0));
}

const isTouch = isTouchDevice();

function myFunction(x) {

  if (x.matches && !isTouch) {

  const section = document.querySelector('section')

  let aimX = 0.5
  let aimY = 0.5
  let currentX = 0.5
  let currentY = 0.5

  const move = (event) => {
    aimX = event.pageX / window.innerWidth
    aimY = event.pageY / window.innerHeight
  }

  const tween = (event) => {
    currentX = currentX + (aimX - currentX) * 0.2
    currentY = currentY + (aimY - currentY) * 0.2

    const sx = section.clientWidth - window.innerWidth
    const sy = section.clientHeight - window.innerHeight

    section.style.transform = `translate(${-1 * sx * currentX}px, ${-1 * sy * currentY}px)`

    requestAnimationFrame(tween)
  }

  tween()
  document.addEventListener('mousemove', move)
  document.addEventListener('touchmove', move)

  }

}

var x = window.matchMedia("(min-width: 1200px)")
myFunction(x)
x.addEventListener(myFunction)

Thank you.

0

There are 0 answers