I have this javascript function and i want it to be active only for screen min-width:1070px. When my page is smaller than 1070px i don’t have the "navbar_top" (i’ve made 2 different headers) so it always add the padding. how can i fix it? can i use media queries?
window.addEventListener('scroll', function() {
if (window.scrollY > 190) {
document.getElementById('navbar_top').classList.add('fixed-top');
} else {
document.getElementById('navbar_top').classList.remove('fixed-top');
document.body.style.paddingTop = 170 + 'px';
}
});
3
Answers
You can use the matchMedia function to check a media query in javascript.
Realistically the easiest way to do this is to just use the media query in the
fixed-top
class. It’ll always get added and removed but whether or not it applies any styling is handled in the CSS rule.Otherwise if it’s for performance reasons and you don’t want the handler running when it doesn’t need to be, you can do it with a named function that you add/remove from the scroll handler on initial execution and again on each window resize.
Also the part of your function that adds padding doesn’t make much sense since the other half of the if condition doesn’t remove it – it seems like either that padding should just always be present or you’re missing something
If the navbar will disappear when the screen shrinks, you can write your code that performs the relevant action instead of the codes we wrote to fix the navbar.