How to toggle between drop down menus in JavaScript without using Jquery

I have multiple lists and each list has its own dropdown feature. I want to make sure that only one dropdown is open at a time. When I click to open one, the currently opened dropdown should close automatically.

function toggleClass(element, className) {
  if (!element || !className) {
    return;
  }

  var classString = element.className,
    nameIndex = classString.indexOf(className);
  if (nameIndex == -1) {
    classString += ' ' + className;
  } else {
    classString = classString.substr(0, nameIndex) + classString.substr(nameIndex + className.length);
  }
  element.className = classString;
}

function dropDown(el) {
  toggleClass(el.nextElementSibling, 'overlayOpen');

}
ul {
  width: 200px;
}
li {
  margin: 0;
  font-size: 20px;
  line-height: 50px;
  width: 100%;
  cursor: pointer;
  background-color: red;
  overflow: hidden;
}
.overlayOpen {
  opacity: 1 !important;
  height: 50px !important;
  width: 100% !important;
}
.overlay {
  width: 100%;
  z-index: 1000;
  background-color: green;
  overflow: hidden;
  max-width: 800px;
  opacity: 0;
  height: 0;
  width: 0;
  -webkit-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  -moz-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  -o-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  -ms-transition: width 0.2s, height 0.2s, opacity 0.2s ease;
  transition: width 0.2s, height 0.2s, opacity 0.2s ease;
}
<ul>
  <li id="1" onclick='dropDown(this)'>example</li>
  <li id="overlay_1" class='overlay'>Hidden stuff</li>
</ul>

<ul>
  <li id="2" onclick='dropDown(this)'>example</li>
  <li id="overlay_2" class='overlay'>Hidden stuff</li>
</ul>

Answer №1

To open the clicked element, you can first remove the overlayOpen class from all other elements:

function showContent(element) {
  Array.from(document.querySelectorAll('.overlayOpen'))
       .filter(item => item !== element.nextElementSibling)
       .forEach(item => item.classList.remove('overlayOpen'));
  toggleClass(element.nextElementSibling, 'overlayOpen');
}

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

Tips for altering the appearance of the material-ui slider thumb design when it is in a disabled state

Through the use of withStyles, I have successfully customized the style of the Slider: const CustomSlider = withStyles(theme => ({ disabled: { color: theme.palette.primary.main }, thumb: { height: 24, width: 24, }, }))(Slider); How ...

Create a new variable within a function using an Angular factory

I am working with an Angular factory that generates a function including a variable to select an array for a dropdown. While I have successfully set the variable from a user selection in a controller, I am facing difficulties getting this variable into the ...

Node.js experiencing CORS problem causing failure

app.use(function (req, res, next) { // Allowing connection to a specific website res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8100'); // Allowing specific request headers res.setHeader('Access-Co ...

OpenLayers: real-time data display of objects from a list

When working with OpenLayers, I encountered an issue where my object was undefined and I couldn't retrieve the information I needed to display feature data on the map. Initially, I passed a list from the controller to my JSP file and attempted to use ...

jQuery - accessing a different class within the object

Let me explain the scenario: I have a website that will delve into 4 different subjects. Initially, I have 4 divs each representing the title of those subjects. For instance, <div><p> Physics </p></div> <div><p> Chem ...

The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Creating a unique SVG pattern starting from the center

I'm currently working on implementing a grid pattern that spans the entire viewport, following this solution. Although the grid starts from the top-left corner of the viewport, my goal is to have it start from the middle of the screen instead. This w ...

Hover Effect in JavaScript

After thoroughly checking all the duplicates below, I still couldn't quite figure out how to achieve the desired effect. Here are some resources I looked into: make animation hover like transition hover JS hover-like animation Hover animation with js ...

Making a tooltip in Angular programmatically

When hovering over an SVG element, I want to display a tooltip. I prefer the tooltip to be an Angular component for streamlined UI development. The challenge arises when the SVG element is dynamically generated, making it difficult to create a template r ...

Getting directions using the node-googlemaps module in node.js can be achieved by following these steps

For the past day, I've been attempting to make progress with this Node.js Google Maps directions example, but so far, no success. Every time I run it, I keep seeing ·· √ OK » 2 honored (0.848s). I've previously asked a similar question on U ...

Change parent component state using a specific key-value pair

Within my React application, I am struggling to modify the parent component from a child component. I want to achieve this by calling a function in the parent component and passing both a key and a value. Here is an example of what I have attempted: var F ...

Tips on reversing a numeric value with scientific notation in nodeJS

Exploring the optimal method to reverse an integer (positive and negative) in NodeJS 12 without the need to convert the number to a string. This solution should also accommodate numbers written in scientific notation such as 1e+10, which represents 10000 ...

Transferring information to the controller and refreshing the interface (Single-page design)

I'm stuck on a personal project and could really use some help. If anyone has any feedback, it would be greatly appreciated. Thanks in advance. In my index.php file, I have a div with the id main-container. Inside this container, there are two separa ...

Tips for eliminating delays in removing CSS transitions

Is there a way to smoothly transition a CSS property, make an immediate change in the CSS property value, and then reattach the transition without any delay? To better understand, consider the following example: if ($(".marquee").height() < $(".marqu ...

Step by step guide to showcasing images dynamically in user interface

My current project involves displaying a screen with an HTML table and an image. The HTML table is fully dynamic. The Code Working Process When the user loads a page (with a URL), I render an HTML table in different parts as the page loads. I retrieve al ...

The Angular directive was unable to reach the controller located higher up in the DOM hierarchy

template <section id="content" ng-controller="ReservationController as resvnCtrl" > <form role="form" name="resvnCtrl.form"> <div data-date-picker> </div> ...

Exploring the power of the spread operator in event listeners within VueJS 2 and JSX

Let me simplify my issue for you: render (h) { let events = {onClick: handleClick} return (<div {...events}></div>) } The onClick event did not get added to the div element. The spread operator works well with class and style attributes b ...

How to use the zip iterable to create multiple rows in a table using ReactJS

I have a collection of arrays that I need to unpack and insert into a table. For instance, I will have an array named a=[1,2,3,4] and b=['a','b','c','d'], both with the same length. Initially, I have a table with o ...

Switch between images using JavaScript or JQuery

I am looking for a way to switch between "edit.png" and "ok.png" images on my web page. When the page initially loads, it displays buttons with "edit.png" images, as shown in the screenshot https://i.sstatic.net/QmgdM.png My goal is to have the image rema ...