Search code examples
javascriptmedia-queriesaddeventlistener

addEventListener in JS does not work properly


I am making a Web Site in which I want to shrink the navigation bar on the first scroll, but I want that to happen only on desktop.

I am using a mediaQuery.addEventListener to look for change in the viewport size, but when I shrink the width of the page, it still shrinks the nav-bar, it stops that only when I refresh the page, and when I resize the window back to full width, it shrinks itself again as it should, but without the need to refresh.

const mediaQuery = window.matchMedia("(min-width: 992px)")
handleDeviceChange(mediaQuery);
mediaQuery.addEventListener("change", handleDeviceChange);
function handleDeviceChange(e) {
    if (e.matches) {
        //code that shrinks nav-bar on first scroll
          }
      }
    }
  }

Solution

  • you can add resize listener to visualViwport to detect viewport width on change. here is how:

    var nav = document.getElementById("nav");
    var vp = visualViewport;
    
    vp.addEventListener("resize", function () {
    
        if (vp.width <= 400) {
    
           // console.log(vp.width);
            nav.style.background = "red";
            nav.style.height = "100px";
        }
        else {
    
            nav.style.background = "lightcoral";
            nav.style.height = "150px";
        }
    });
    #nav {
        width: 100vw;
        height: 150px;
        border: 1px solid;
        background: lightcoral;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    <nav id="nav">nav</nav>