Search code examples
javascriptcss

How can i activate this javascript function only for a specific width?


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';
    }
});

Solution

  • 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.

    //your function
    function handleScroll() {
        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';
        }
    }
    // size control
    function checkScreenWidth() {
        if (window.matchMedia('(min-width: 1070px)').matches) {
            window.addEventListener('scroll', handleScroll);
        } else {
            window.removeEventListener('scroll', handleScroll);
            // If the navbar is not fixed when the screen is minimized
            navbar.classList.remove('fixed-top');
            document.body.style.paddingTop = '0';
        }
    }
    
    checkScreenWidth();
    
    window.addEventListener('resize', checkScreenWidth);