The drop-down menu keeps flickering instead of remaining open when clicked

I am facing an issue with a dropdown menu in my webpage. The menu is initially hidden, but should become visible when the list element containing it is clicked. I have written JavaScript code to add a class that changes the visibility property to visible upon clicking. However, the problem I encountered is that the visibility only changes for a brief moment and then reverts back to hidden. How can I modify the code so that the dropdown menu remains visible after the initial click until the next one?

document.querySelector('#drop').addEventListener('click', (e) => {
    document.querySelector('.sub-men').classList.toggle('visible');
})
  
    
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

nav {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    height: 10vh;
    background-color: aquamarine;
}
.logo {
    display: flex;
    align-items: center;
    margin-left: 10px;
}

.main-menu {
    display: flex;
    list-style: none;
    align-items: center;
}

.main-menu > li {
    position: relative;
    height: 10vh;

    
}

.main-menu > li > a {
    display: flex;
    padding: 0 1rem;
    text-decoration: none;
    background-color: antiquewhite;
    height: 10vh;
    align-items: center;
}

.sub-men {
    display: flex;
    flex-direction: column;
    position: absolute;
    list-style: none;
    visibility: hidden;
    
}

.sub-men > li {
    position: relative;
    background-color: aquamarine;
    padding: .5rem 1rem;
    width: 100px;
    text-align: center;
    
}

.visible {
    visibility: visible;
}

.sub-men > li:hover {
    background-color: aqua;
}

.sub-men > li > a {
    text-decoration: none;
    position: relative;
   
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="stylesheet" href="styles.css">
    <script src="jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <nav>
        <h1 class="logo">Logo</h1>
        <ul class="main-menu">
            <li><a href="">Link 1</a></li>
            <li><a href="" id="drop">Link 2</a>
            <ul class="sub-men">
                <li><a href="">Sub-1</a></li>
                <li><a href="">Sub-1</a></li>
                <li><a href="">Sub-1</a></li>
            </ul>
            </li>
            <li><a href="">Link 3</a></li>
        </ul>
    </nav>
    <script src="index.js"></script>
  </body>
</html>

Answer №1

Using only CSS, you can achieve this effect, but it lacks keyboard accessible navigation

To implement this, simply remove the JavaScript and add

.main-menu li:hover .sub-men {visibility: visible;}
to your CSS. (I have tested this with multiple drop-down menus)

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

nav {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  height: 10vh;
  background-color: aquamarine;
}

.logo {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.main-menu {
  display: flex;
  list-style: none;
  align-items: center;
}

.main-menu>li {
  position: relative;
  height: 10vh;
}

.main-menu>li>a {
  display: flex;
  padding: 0 1rem;
  text-decoration: none;
  background-color: antiquewhite;
  height: 10vh;
  align-items: center;
}

.sub-men {
  display: flex;
  flex-direction: column;
  position: absolute;
  list-style: none;
  visibility: hidden;
}

/* makes sub-men visible when its parent is hoverd. */
.main-menu li:hover .sub-men {
  visibility: visible;
}

.sub-men>li {
  position: relative;
  background-color: aquamarine;
  padding: .5rem 1rem;
  width: 100px;
  text-align: center;
}

.visible {
  visibility: visible;
}

.sub-men>li:hover {
  background-color: aqua;
}

.sub-men>li>a {
  text-decoration: none;
  position: relative;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>HTML 5 Boilerplate</title>
  <link rel="stylesheet" href="styles.css">
  <script src="jquery-3.6.0.min.js"></script>
</head>

<body>
  <nav>
    <h1 class="logo">Logo</h1>
    <ul class="main-menu">
      <li><a href="">Link 1</a></li>
      <li><a href="" id="drop">Link 2</a>
        <ul class="sub-men">
          <li><a href="">Sub-1</a></li>
          <li><a href="">Sub-1</a></li>
          <li><a href="">Sub-1</a></li>
        </ul>
      </li>
      <li><a href="">Link 3</a></li>
    </ul>
  </nav>
  <script src="index.js"></script>
</body>

</html>

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

Position the float input to the right on the same line as an element

This Angular code contains a challenge where I aim to have text at the start of a column and an input box on the right side of the page, both aligned on the same line. The issue lies in the code which floats the input to the right but disrupts the alignme ...

Changing the InnerHTML of a tag in JavaScript using class and id attributes

When it comes to handling these links <div class="post_actions"> <a class="color-transition article_delete" href=""><i class="fa fa-pencil"></i></a> <a class="color-transition article_edit" href="#" id="1">< ...

The initial row's Id will be used as the Id for all subsequent rows within a JSON object

After dragging a tr in a table and confirming by clicking a button, I need the order list to be updated in the database. To achieve this, I created a JSON object where I intend to save the ids and their corresponding new orders. The issue I am facing is t ...

Is it possible to configure Nginx to provide HTTPS on port 10000 and implement Basic Auth for an Express app?

My Linux NodeJS/Express application is designed to serve a text file located at http://example.com/secret.txt. I am looking to restrict access to this file only over HTTPS on port 10000 with Basic Auth security measures in place. It's important to no ...

I'm noticing that when I refresh the page, my inputs seem to disappear from the page, yet I can see that they are saved in the console's local

If anyone can help me with this issue I'm facing, I would greatly appreciate it. My aim is to retain values in the text box along with local storage even after refreshing the page. Here is an example of the code I am working with: Link to my web appl ...

The input field is failing to show up on the screen

I have been working on my React app and experimenting with how to dynamically display input elements based on different screen sizes. To achieve this, I implemented the use of window.innerWidth as shown in the code snippet below: <div className='Tr ...

Show the image using material-ui-dropzone

Currently, I am engaged in a ReactJS project where I have implemented material-ui-dropzone to upload and exhibit an image. The uploading part has been successfully completed. However, my current obstacle lies in figuring out how to display this uploaded im ...

programming for the final radio button text entry

I am struggling with a form that has 5 radio buttons, including an "other" option where users can manually enter text. The issue I'm facing is that the form only returns the manual entry text and not any of the preset radio values. I need it to work f ...

Troubleshooting Jquery Ajax Failure in Laravel 4

Whenever I utilize jQuery Ajax to insert data into the database, a peculiar issue arises. Upon clicking the submit button, my page mysteriously returns blank. To shed light on this dilemma, I decided to employ Firebug for debugging purposes, only to stumbl ...

Sharing information with Django through Ajax and jQuery

I'm facing an issue with posting html5 geolocation data to the django admin backend. I've managed to display the latitude and longitude on the html page but can't seem to successfully submit the data to django. I suspect there might be a pro ...

Why are @Inject and Injectable important in Angular's Dependency Injection system?

constructor(private smartphoneService: smartphoneService) { } Although I am able to execute the code above without encountering any errors, I find myself pondering on the necessity of using @Inject and Injectable on services, Pipes, and other components. ...

Setting up eslint for your new react project---Would you like any further

I am currently working on a TypeScript-based React application. To start off, I used the following command to create my React app with TypeScript template: npx create-react-app test-app --template typescript It's worth noting that eslint comes pre-co ...

The database powered by Postgresql performs flawlessly when it comes to updating data with accurate code execution. However, there seems to be an

Imagine a zoo with a postgresql database. To enable web access to this database, I am using php and javascript. Most of the web pages are working fine, but I am currently working on a page where clients can add or remove animals from existing exhibits. T ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Switching the keyboard language on the client side of programming languages

I'm interested in altering the keyboard language when an input element changes. Is it possible to modify the keyboard language using client-side programming languages? And specifically, can JavaScript be used to change the keyboard language? ...

Is it possible to apply an onclick event to list items using Ajax and jQuery?

This particular code block functions correctly: $(document).ready(function () { $.getJSON('./record.json', function (data) { var studentsHTML = '<ul>'; $.each(data, function (index, student) { stude ...

Dynamic placement of divs when new content is added to the page

Before we begin, I'll provide you with the complete HTML code of my webpage: <div align="center"> <img src="http://questers.x10.bz/Header.png" style="position: absolute; margin-left: -440px; box-shadow: 0px 3px 12px 2px #000;" class="rotate" ...

How can you prevent videos from constantly reloading when the same source is used in multiple components or pages?

How can we enhance loading performance in Javascript, React, or Next JS when utilizing the same video resource across various components on different pages of the website to prevent unnecessary reloading? Is there a method to store loaded videos in memor ...

Obtaining the latest state within the existing handler

In my React application, I have a handler that shuffles the state entry data: state = { data:[1,2,3,4,5] }; public handleShuffle = () => { const current = this.state.data; const shuffled = current .map((a: any) => [Math.random() ...

Challenge encountered when attempting to detect multiple submit buttons using jQuery

I am currently attempting to identify which of the four submit buttons was clicked using jQuery 1.7.2. When any one of three specific buttons is clicked, I want an alert box to appear displaying the value of that particular button. Below is the HTML code s ...