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

troubleshooting Axios errors in React applications

User/Project.js: import React, { useState, useEffect } from "react"; import Axios from "axios"; const Project = () => { const [projectName, setprojectName] = useState(""); const [projectDescription, setprojectDescriptio ...

Troubleshooting JSONP Implementation with JQuery: Scope versus Async Problems

I've been trying to call a JSONP service using the $.ajax function: $.ajax({ url: jsonpURI, dataType: "jsonp", jsonpCallback: callback, success: function () { console.log("Success"); }, error: function (err) { ...

Looping through arrays using ng-repeat

{ "employees" : [ { "name" : "XXX", "id" : "1", "Salary" : [ { "Month" : "XXXX", "Amount" : "XXXX", }, { "Month" : "XXXX", "A ...

Is there a way to select an element within a nested list item only when the preceding list item is clicked using Jquery/JavaScript?

I am working with an unordered list that looks like this: <ul> <li><a class="foo" id="one">some text</a></li> <li><a class="foo" id="two">some text</a></li> <li><a class="foo" id="thr ...

Determine the shared elements within a single array by utilizing Javascript

I have the following array of mergeUniqueItems: var mergeUniqueItems = ["-JsDEcxz_ZSGFLKwd1QM", "-JsJ2NXGDYKI6QRsuXVK", "-JsJ2RK-kOG2eGcG04xF", "-JsJ2RK-kOG2eGcG04xF", "-JsJ2YLPiP6751zh8geS"] After using this code snippet, I encountered an issue: ...

Combining Two Eloquent Objects in Laravel 4.2 Based on Index

Hey everyone, I could really use your assistance with a project I'm working on using the outdated version of Laravel 4.1. Here's the situation: I have two Eloquent objects that are not related to each other. I want to combine data from these two ...

C# - Issue with Webbrowser failing to fully load pages

I am facing an issue with loading pages completely on the web browser, likely due to heavy usage of JavaScript. To address this problem, I have integrated another browser into the project called Awesomium. I am wondering if Awesomium supports using getEle ...

When a named capture group is included in the regex of a GET path, Express crashes with the error message: "Cannot read property 'name' of undefined at Layer

I am looking to process a GET request and extract specific information from the URL. Let's consider this scenario: const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\ ...

The use of the picture element, with its ability to support various image formats and sizes, must always include

Recently, I came across a VueJS template that closely resembles HTML but has the following structure: <picture> <source type="image/avif" :scrset="avif" /> <source type="image/webp" :scrset="webp" ...

What is the best way to add a radial pattern to a ring using three.js r67?

I am facing a challenge in applying a texture to a ringGeometry using three.js r67. The issue lies in orienting the texture correctly. My goal is to apply a specific texture to a ringGeometry mesh in a radial manner, where the blue end of the texture align ...

JS-generated elements do not automatically wrap to the next line

For my first project, I've been working on a to-do list and encountered an issue. When I create a new div with user input, I expect it to start on a new line but it remains stuck on the same line. Can anyone point out where I might have gone wrong? I ...

Could someone provide an example to illustrate the concept of "em is relative to the font size and % is relative to the parent element"?

Could someone provide an example of how "em is relative to the font size and % is relative to the parent element" works? What exactly do "relative to the font size" and "relative to the parent element" mean? ...

Utilize Bootstrap cards to display images across the full width of the page

I am using the Bootstrap card component https://getbootstrap.com/docs/4.0/components/card/ to display an image. The issue I'm facing is that on the Bootstrap template, it adds a margin around the image. I would like the image to take up the full width ...

Is there a way to use jQuery draggable to move a zoomed image within a div clipping mask?

Looking to enhance user experience, I am developing an interface that allows users to zoom in on an image and move the zoomed version within a clipping mask div. I have created a div with dimensions of 200px by 200px and set overflow: hidden. Then, I inse ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

Revolutionizing Zen Cart with slimMenu

Is there a smarter person out there who can help me understand why the slimMenu is breaking when I add these files to the bottom of the page? <link href="includes/templates/westminster_new/css/age-verification.css" rel="stylesheet"> <script src=" ...

Tips for utilizing a select in a jQuery function

Recently, I've been working on some JavaScript code that involves appending options to select elements. Here is an example: var myuniqueddl = $('#myuniqueddl'); $("<option value='0'>--- Select a value ---</option>").a ...

Are there any alternatives to ui-ace specifically designed for Angular 2?

I am currently working on an Angular2 project and I'm looking to display my JSON data in an editor. Previously, while working with AngularJS, I was able to achieve this using ui-ace. Here is an example of how I did it: <textarea ui-ace="{ us ...

Achieving priority for style.php over style.css

Having trouble with theme options overriding default CSS settings in style.css. Here's what I have in my header.php: <link rel='stylesheet' type='text/css' media='all' href="<?php bloginfo( 'stylesheet_url&apo ...