What is the best way to apply CSS to a class only when another class is also present on the element?

In my view, I have the following code snippet:

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

The elements "Slidedown" and "Slideup" appear based on user interaction. Currently, I have a height of 440px set for bottom-nav which seems excessive. I only want this height to be applied if Slidedown is present and the screen size is under 768px. Any suggestions on applying CSS styles to one class based on the presence of another class?

I've attempted the following approach which didn't work:

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

This failed because it targeted slidedown instead of bottom-nav.

My JavaScript file includes:

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;")
}

Although I thought this condition would work, it caused issues throughout the page.

Another attempt I made was:

    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;")
     }
   };

However, this disrupted other JavaScript functions on the page.

Answer №1

Great effort! Instead of completely overwriting the entire style attribute for your bottom element, try adjusting only the height property. Similarly, instead of replacing the entire value of the className for the menu, consider adding and removing classes dynamically:

const 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';
  }
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS delays affecting the loading of the page's display

I am currently working on a WordPress website and I have noticed that one of the CSS files takes approximately 10 seconds to load, causing a significant delay in displaying the page. I am looking for ways to speed up this loading process. As part of my ef ...

Issue with Java Script inheritance in google.maps.OverlayView not functioning as expected

UPDATE: After spending another day working on this, I believe I have identified the issue, although it is not yet confirmed. Once I have verified the solution, I will update this post with an answer. My current understanding is that the problem arises fro ...

Ways to transfer property values between two instances of a component

Two datepicker components are present, one for "From" date and another for "To" date. If the "To" date is empty, I want to automatically update it with the value from the "From" date. I have considered using 'emit' on the value but I am unsure ...

What is the best way to align two boxes horizontally, with one positioned directly beneath the other?

The code remains unchanged, the only difference is that it does not align properly with the box above. Thank you in advance. CSS #menu { margin-top:75px; min-width:19px; max-width:1920px; height:40px; background-color:#0F0; border:4px groove #F00; } #h ...

Click on the bootstrap carousel to dynamically load images

I am currently developing a website with numerous images, and in order to enhance loading time, I plan to have hidden images load when the user clicks on the cover image using JavaScript. Subsequently, these images will be inserted into a Bootstrap carouse ...

Angular module now equipped with web worker for independent operation

My goal is to create a standalone AngularJS module that utilizes web workers for handling heavier processing tasks. This module will be integrated into an Angular web application that I am currently developing, as well as potentially other projects. I env ...

Unknown Parameters Issue with Vue.js Router Links

Within my Vue.js project, I am utilizing params in my navigation.vue component to pass data onto the next page for dynamic routing purposes. Below is an example of how I am using this: <router-link tag="p" :to="{name: 'Main', ...

Validating optional fields in React

My registration form includes the following fields: Name Email Password Confirm password Optional field Select role (student, professor, secretary) Here's what I'm trying to achieve: If I want to create a user with a student role, the optional ...

Creating static pages using React

I am aiming to have my React application operating on the client-side through Amazon S3 (CDN), with news files being created in order to incorporate meta tags for social media sharing, particularly with Facebook. For instance, when a user shares , I envis ...

How can I use try-catch in JavaScript to call the same function again in the catch block

When encountering a scenario in JavaScript where a Try Catch block fails due to some issue, what is the best approach to handle this and retry the same operation until it is successful? For example: const getMyDetails = async()=>{ try{ await ge ...

What could be causing my HTML website to load slowly and freeze when I switch to another program?

I am in the process of creating three websites. Two of them are functioning perfectly fine, but I am encountering a speed issue with the third one. Sometimes it loads slowly initially, but if I wait a bit longer, it eventually loads and works well. However ...

What is the correct property for accessing and changing the value of a Text node: data or nodeValue?

What is the best option to use? The website suggests using nodeValue, although data shows better compatibility. ...

The menu positioned beneath the logo is malfunctioning

Upon downloading a template from the internet, I created a menu at the top with the logo positioned below it. However, when scrolling down, the menu items were supposed to turn black with a white background, resembling this: https://i.sstatic.net/1HTLZ.jp ...

JavaScript array push is not functioning as expected

Having trouble getting my push function to work properly.. Here is my code snippet: var result = {}; dpd.timesheetsdone.get(function (timesheets, err) { if(err) return console.log(err); timesheets.forEach(function(entry, index) { result[ent ...

Using CSS pseudo elements (`:before` and `:after`) to display SVG icons that can be easily re-used and self-hosted

Exploring Self-Hosting Static Assets After coming across an article about the risks of using CDN's or external infrastructure for hosting static assets, I started considering self-hosting fonts and icons myself. I know you can self-host fonts by dow ...

Transform markdown into HTML code

Is there a way to effectively transform a string that resembles the following format: '* [-]Tree Item1', '** [-]Tree Item1-1', '*** Tree Item1-1-1', '*** Tree Item1-1-2', '*** Tree Item1-1-3', '** Tre ...

Combining several meshes in ThreeJS while maintaining distinct materials

I seem to be facing a dilemma. I am attempting to consolidate several meshes into one in order to optimize draw calls. Each mesh I have comes with its own unique material, whether it be color or texture. Below is the snippet of code I have been working on ...

What is the reason behind shadow dom concealing HTML elements when viewed in inspect mode?

https://i.stack.imgur.com/UZM7f.png Monday.com has implemented Shadow Dom to protect its source code. How can I work around this limitation? ...

Material-UI style is taking precedence over custom React Component styles

RELATED QUESTION ON THIS LINK: Styles being overwritten by Material-UI style I am currently developing a component library based on Material UI. I want to pass styles to my custom components using JSS. However, I am facing challenges with the higher speci ...

Inquiring about the presentation of text using HTML and CSS

I am looking for a simple fix to make a line of HTML display exactly as follows: 22 West Washngton St. Northbrook, IL 39492 Instead of: 22 West Washington St. Northbrook, IL 39492 Can someone guide me on how to remove the space between the lines of ...