How to insert media query in vanilla js?

How to run this javascript on SP view only.

const navTrigger = document.querySelector('.nav__trigger');
const nav = document.querySelector('nav');

navTrigger.addEventListener('click', event => {
    event.preventDefault();
    navTrigger.classList.toggle('nav__trigger--active');
    nav.classList.toggle('nav--open');
    const mediaQuery = window.matchMedia('(min-width: 768px)')
    document.body.classList.toggle('overflow'); // THIS CODE
});

2 answers

  • answered 2020-11-25 07:22 54ka

    The matchMedia() Find out if the screen is less than or greater than 768 pixels wide. And if the condition is met executes the code

    const navTrigger = document.querySelector('.nav__trigger');
    const nav = document.querySelector('nav');
    
    navTrigger.addEventListener('click', event => {
        event.preventDefault();
        navTrigger.classList.toggle('nav__trigger--active');
        nav.classList.toggle('nav--open');
    
        if (window.matchMedia("(min-width: 768px)").matches) {
            document.body.classList.toggle('overflow'); // THIS CODE
        }
    });
    

  • answered 2020-11-25 07:45 Daniel Smith

    Listen for changes

    // Create a condition that targets viewports at least 768px wide
    const mediaQuery = window.matchMedia('(min-width: 768px)')
    
    function handleTabletChange(e) {
      // Check if the media query is true
      if (e.matches) {
        // Then log the following message to the console
        console.log('Media Query Matched!')
      }
    }
    
    // Register event listener
    mediaQuery.addListener(handleTabletChange)
    
    // Initial check
    handleTabletChange(mediaQuery)
    

    more example

    // 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
        }
    }