How do I conditionally apply CSS to a class if a different class is present?

Viewed 1087

I have the following in the view:

<div class="bottom-nav container-fluid">
 <div class="container">
  <div class="row mobile-menu-row">
   <div class="col"></div>
  </div>
  <div class="row mobile-menu-row">
   <div class="slidedown"></div>
  </div>

Slidedown and Slideup are both present depending on the user clicking on the button. At the moment I have a height of 440px applied to bottom-nav that is massive and really only want to be present on bottom-nav if Slidedown is present and the screen size is under 768px. Any suggestion on only applying CSS styling on another class if a class appears?

Attempts that I've tried that definitely didn't work:

@media and (max-width: 767px) {
  .bottom-nav .slidedown{
   height: 440px; 
  }
 }

This naturally doesn't work because it's applying it to slidedown and not the bottom-nav section.

My JS file has:

const nav = () => {
const mobileButton = document.querySelector('a.mobile-button');
const menu = document.querySelector('.mobile-menu-cont');
const regionLink = document.querySelector('.mobile-menu-row ul > li');
const regionMenu = document.querySelector('.mobile-menu-row ul > li > ul');
const bottom = document.getElementsByClassName('bottom-nav');

function init() {
  mobileButton.addEventListener('click', toggleMenu);
  regionLink.addEventListener('click', toggleSubMenu);
}

let toggleMenu = (e) => {
  e.preventDefault();
  if (menu.classList.contains('slideup')) {
    menu.classList = 'slidedown';
  } else {
    menu.classList = 'slideup';
  }
};
if (menu.classList = 'slidedown'){
  bottom.setAttribute("style", "height: 440px;")
} else {
  bottom.setAttribute("style","height: 0;")
}

I thought the condition would work but it appears to just break many different things on the page.

I've also tried:

    let toggleMenu = (e) => {
     e.preventDefault();
     if (menu.classList.contains('slideup')) {
       menu.classList = 'slidedown';
       bottom.setAttribute("style", "height: 440px;")
     } else {
       menu.classList = 'slideup';
       bottom.setAttribute("style", "height: inherit;")
     }
   };

This messes up a lot of my other JS on the page.

1 Answers

You were close! Instead of squashing the full style attribute of your bottom elem, just set the height property, and likewise, instead of replacing the className of menu, just add to and subtract from the class name:

let toggleMenu = (e) => {
  e.preventDefault();
  if (menu.classList.contains('slideup')) {
    menu.className = menu.className.replace('slideup', '');
    menu.className += ' slidedown';
    bottom.style.height = '440px';
  } else {
    menu.className = menu.className.replace('slidedown', '');
    menu.className += ' slideup';
    bottom.style.height = 'inherit';
  }
};
Related