I am trying to run a function when the window is resized and hits a certain size. The following was working perfectly:
JavaScript
x
4
1
var mediaQuery = window.matchMedia("(max-width: 480px)")
2
mobileSlider(mediaQuery) // Call listener function at run time
3
mediaQuery.addListener(mobileSlider) // Attach listener function on state changes
4
However, I got a warning that addListener
is deprecated, so I’m attempting to change it without much success. I have tried the below, but doesn’t work. What should I be doing?
JavaScript
1
4
1
var mediaQuery = window.matchMedia("(max-width: 480px)")
2
mobileSlider(mediaQuery) // Call listener function at run time
3
window.addEventListener('resize', mobileSlider) // Attach listener function on state changes
4
I have also tried window.addEventListener('resize', mobileSlider(mediaQuery))
without success.
Advertisement
Answer
You could try adding an event listener on the change
event from MediaQueryList.
I think this might help with your issue, please have a look here: https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList#examples