0

Im trying to toggle a click event listener using matchmedia. My goal is to add the eventlistener when the screen size is less than or equal 768px and removeEventListener above 768px. The event listener is removed and added when I write them as seperate functions like below:

function clickHandler() {
  alert("media worked");
}

function myFunction(x) {
  if (x.matches) { // If media query matches
    document.getElementById("resources").addEventListener("click", clickHandler)
  } else {
    document.getElementById("resources").removeEventListener("click", clickHandler)
  }
}

var x = window.matchMedia("(max-width: 768px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

HOWEVER, when I write it as a class function below (which is what I need, so that i can remove the myFunction listener later on), the click eventListener gets added, but does not get removed. The console.log of 'smaller screen' and 'wider screen' changes with the width successfully, so i'm thinking it must be something to do with the way I've set up the class function, constructor and/or the methods.

Sorry for the noob question - I've been at it for ages! This is my first time posting so any help/guidance is greatly appreciated.

export default class testController {

constructor(){
this.x = window.matchMedia("(max-width: 768px)")
}

myFunction(e) {
  function clickHandler(){
    console.log("clicked")
  }
  
  if (e.matches) { // If media query matches
    document.getElementById("vid-button").addEventListener("click", clickHandler, false);
    console.log("smaller screen")
  } else {
    document.getElementById("vid-button").removeEventListener("click", clickHandler, false);
    console.log("wider screen")
  }

}


testAdd(){
  this.myFunction(this.x) // Call listener function at run time
  this.x.addListener(this.myFunction) // Attach listener function on state changes
}

testRemove(){
   this.x.removeListener(this.myFunction);
}

}

tController = new testController();
tController.testAdd();

4

0 回答 0