javascripthtmljquerycssdrupal-theming

How to apply a style with on the mobile menu?


On my Drupal 9 website, I activated the Olivero default theme. Here is a demonstration :

https://tugboat-aqrmztryfqsezpvnghut1cszck2wwasr.tugboatqa.com/

I added to my subtheme, the following code :

script.js :

(function ($, Drupal, window, document) {
  $(document).ready(function () {
 
    window.addEventListener("scroll", function() {
      if (document.body.scrollTop > 1 || document.documentElement.scrollTop > 1) {
        document.getElementById("site-header__inner").style.boxShadow = "-36px 1px 36px rgb(0 0 0 / 8%)";
      } else {
        document.getElementById("site-header__inner").style.boxShadow = "none";
      }
    });
      
  });
})(jQuery, Drupal, this, this.document);

The problem is that the style is applied to the mobile menu and the desktop menu. How does this code only apply to the mobile menu ?

When I inspect the page, I find this in css, but I don't know how to use it for the solution of my question :

@media (min-width: 75rem)
body:not(.is-always-mobile-nav).toolbar-horizontal.toolbar-fixed.toolbar-tray-open .site-header__fixable.is-fixed {
    top: 0.4375rem;
}

Solution

  • Adding a class can be done via classList.add(), removing a class is done via classList.remove()

    In your case this would be:

      document.getElementById("site-header__inner").classList.add('shadow-active')
    

    and classList.remove('shadow-active') in the place where you currently have the boxShadow = none function

    If you want to apply styles only to a certain viewport, use mediaqueries for that:

    @media (min-width: 75rem) {
       .shadow-active {  
        box-shadow: -36px 1px 36px rgb(0 0 0 / 8%);
      }
    }