Search code examples
javascriptcssmedia-queries

JS changing attribute based on already set media query


In the following code I am trying to change the dropDown.style.top with already set media query in the css. Essentially I need once when it's desktop layout the value of the style.top to be 4em and if it's in mobile layout (or less than 50em of width) the style.top to be 0. I've already tried with match media but I guess I am missing something. I hope the question makes sense.

Below is the JS function:

window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  let logo = document.getElementById("logo")
  let header = document.getElementById("header")
  let dropDown = document.getElementById("dropdownMenu")
  let mediaQuery = window.matchMedia(('min-width: 50em'))

  if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
    logo.style.width = '4em';
    header.style.background = '#000';
    dropDown.style.top = '2.6em';

  } else {
    logo.style.width = '6em';
    header.style.background = '#0000009d';
    dropDown.style.top = '4em';
  }
}

Thanks!

I tried using the event listeners for media queries but I can't seem to wrap my head around it. I am expecting the dropdown menu once in mobile to fill the entire viewport and once in desktop to behave as normal dropdown menu under the main nav menu.


Solution

  • Actually you do not need the following condition

    document.body.scrollTop > 80 || document.documentElement.scrollTop > 80
    

    Try this one instead for mobile view:

    !mediaQuery
    

    Complete code

    window.onscroll = function () {
      scrollFunction();
    };
    
    function scrollFunction() {
      let logo = document.getElementById("logo");
      let header = document.getElementById("header");
      let dropDown = document.getElementById("dropdownMenu");
      let mediaQuery = window.matchMedia("min-width: 50em");
    
      if (!mediaQuery) {
        logo.style.width = "4em";
        header.style.background = "#000";
        dropDown.style.top = "2.6em";
      } else {
        logo.style.width = "6em";
        header.style.background = "#0000009d";
        dropDown.style.top = "4em";
      }
    }