Skip to content
Advertisement

How to make JS media query work properly?

Media query in JS works, but as soon as it’s nested within a function such as onscroll or onclick, they’ll not work properly.

I’ll just put the code in here just in case you want to resize window easier: https://www.w3schools.com/code/tryit.asp?filename=GP7P1ENXH9JY

Try to test the media query if it works, I know it works, but as soon as you resize it to 768px(desktop) and started scrolling down, it starts to revert back to the tablet media query(600px) and the color changes too, even though the window size is still 768px width. How do I fix this?

JavaScript
JavaScript
JavaScript

Advertisement

Answer

Here is another way to achieve it, the function only handles when the state matches, thus prevent the race condition

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement