skip to Main Content

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


  1. You can use the matchMedia function to check a media query in javascript.

    const matches = window.matchMedia("(min-width: 1070px)");
    if(matches) {
        // Do your stuff
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search