简体   繁体   中英

Include CSS Media Query in Javascript Event Listener

I have this javascript code that enables the top navigation of my website shrink. See below:

<script>
        function init() {
            window.addEventListener('scroll', function(e){
                var distanceY = window.pageYOffset || document.documentElement.scrollTop,
                    shrinkOn = 300,
                    header = document.querySelector("header");
                if (distanceY > shrinkOn) {
                    classie.add(header,"smaller");
                } else {
                    if (classie.has(header,"smaller")) {
                        classie.remove(header,"smaller");
                    }
                }
            });
        }
        window.onload = init();
    </script>

The code adds the class "smaller" to the header section when the window is scrolled down the specified distance and reduce it when scrolled back up. However, I want the class to be added and removed only when the screen is larger than 768px (ie min-width: 768px). On smaller screen size, I do not want the add and remove class to work.

I saw an example of the code to use but I am not sure how to add it to my code above.

// media query event handler
if (matchMedia) {
  const mq = window.matchMedia("(min-width: 500px)");
  mq.addListener(WidthChange);
  WidthChange(mq);
}

// media query change
function WidthChange(mq) {
  if (mq.matches) {
    // window width is at least 500px
  } else {
    // window width is less than 500px
  }

}

Any help on how to combine this will be appreciated.

from what you describe, you're wanting to add your existing code inside the conditional, so:

// media query event handler
    if (matchMedia) {
      const mq = window.matchMedia("(min-width: 768px)");
      mq.addListener(WidthChange);
      WidthChange(mq);
    }

    // media query change
    function WidthChange(mq) {
      if (mq.matches) {
        [[ YOUR CODE ]]
      } else {
       [[ UNBIND SCROLL LISTENER ]] 
      }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM