How to add media query in JS?

How to add condition to this code worked only with media (min-width: 769px)?

function init() {
 window.addEventListener('scroll', function(e) {
 var header;
 var distanceY = window.pageYOffset || document.documentElement.scrollTop,
 shrinkOn = 1,
 header = document.getElementById("name");
 if (distanceY > shrinkOn) {
header.classList.add("red");
 } else {
 if (header.classList.contains("red")) {
header.classList.remove("red");
}
}
});
}
window.onload = init();
July 4th 19 at 23:08
2 answers
July 4th 19 at 23:10
Solution
ask the class "red" in the css only in the media. and nowhere else
tobish class will be added always. but it will work only in the right permissions
I did not know that so easy, thank you) - Abbey commented on July 4th 19 at 23:13
July 4th 19 at 23:12
Solution
If you do so, then:
1. do not hang an extra processor that will work always, even when not needed (tobish pieces)
2. no need to stand in the media (the class will not be hung on the gamers), although it is possible there to leave

function init() {
if (window.innerWidth >= 769) {
 window.addEventListener('scroll', function(e) {
 var header;
 var distanceY = window.pageYOffset || document.documentElement.scrollTop,
 shrinkOn = 1,
 header = document.getElementById("name");
 if (distanceY > shrinkOn) {
header.classList.add("red");
 } else {
 if (header.classList.contains("red")) {
header.classList.remove("red");
}
}
});
}
}
window.onload = init();


the downside is that if you are debugging adaptiv by stretching the browser in different directions, in order to make the code work when resize from smallest to largest (when the page is initially opened a little), you need to refresh the page.
Thanks, I'll try that. - Abbey commented on July 4th 19 at 23:15

Find more questions by tags JavaScript