Conceal a dropdown menu with a single click

I want the dropdown to disappear temporarily after I make a selection, but still be available for me to hover over later.

This is my current code:

<div class="navbutton_container">
    <button onclick="someFunction()"><p>Title</p></button>
    <div class="nav_dropdown">
        <button onclick="someFunction()"><p>Content1</p></button>
        <button onclick="someFunction()"><p>Content2</p></button>
        <button onclick="someFunction()"><p>Content3</p></button>
        <button onclick="someFunction()"><p>Content4</p></button>
    </div>
</div>
.navbutton_container > .nav_dropdown {
    display: none;
    opacity: 0;
}
.navbutton_container:hover > .nav_dropdown {
    display: block;
    opacity: 1;
    position: absolute;
}

Once a button is selected, I would like the dropdown to disappear temporarily so it's not in the way until they stop hovering over it. Then, when they hover back on it, the :hover property should work again.

If you have suggestions for a better structure, I'm completely open to making changes!

Answer №1

One approach to achieve the desired functionality is by using a combination of CSS classes and mouseout event detection.

function showHideDropdown() {}

window.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.navbutton_container').forEach(el => el.addEventListener('mouseover', e => {
    let target = e.target.classList.contains('navbutton_container') ? e.target : e.target.closest('.navbutton_container');
    target.querySelector('.nav_dropdown').classList.remove('hold');
  }))
  document.addEventListener('click', e => {
    if (e.target.closest('.nav_dropdown')) {
      e.target.closest('.nav_dropdown').classList.add('hold')

    }
  })
})
.navbutton_container>.nav_dropdown {
  display: none;
  opacity: 0;
}

.navbutton_container:hover>.nav_dropdown {
  display: block;
  opacity: 1;
  position: absolute;
}

.navbutton_container:hover>.nav_dropdown.hold {
  display: none;
  opacity: 0;
}
<div class="navbutton_container">
  <button onclick="showHideDropdown()" class='toggler'><p>Title</p></button>
  <div class="nav_dropdown ">
    <button onclick="showHideDropdown()"><p>Content1</p></button>
    <button onclick="showHideDropdown()"><p>Content2</p></button>
    <button onclick="showHideDropdown()"><p>Content3</p></button>
    <button onclick="showHideDropdown()"><p>Content4</p></button>
  </div>
</div>
<div class="navbutton_container" style='margin-top:100px'>
  <button onclick="showHideDropdown()" class='toggler'><p>Title</p></button>
  <div class="nav_dropdown ">
    <button onclick="showHideDropdown()"><p>Content1</p></button>
    <button onclick="showHideDropdown()"><p>Content2</p></button>
    <button onclick="showHideDropdown()"><p>Content3</p></button>
    <button onclick="showHideDropdown()"><p>Content4</p></button>
  </div>
</div>

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

Objects become visible over a sphere only when they are positioned behind it

I am currently working on a project to create a dynamic rotating globe with points of interest marked on it. The globe rotates, and I want the points of interest to be visible whenever they are in view. However, I am facing an issue where the points of in ...

The Nestjs cronjob is having trouble accessing the injected service

After setting up a cronjob to call a service from another module, I encountered an issue where the console logged items were displaying correctly when running the method manually from the endpoint. However, once I added back the cronjob decorator, the serv ...

Display additional text when hovering over an object

Is there a way to make my text expand and display all of its content when hovered over, especially for those sections that are longer than the div size? I currently have some code implemented, but it seems to reveal the text horizontally. I am looking fo ...

Unable to perform the 'setSelectionRange' function on the 'HTMLInputElement' due to the input element's type being 'number', which does not allow selection

My attempt to enable text selection in an input box upon user click by using the code snippet below was unsuccessful: <input type="number" onclick="this.setSelectionRange(0, this.value.length)" name="quantity" /> Instead of achieving the desired ef ...

Transforming an image into a CSS-powered website menu button: Step-by-step guide

I am currently using images as button backgrounds, and I have programmed them to change when the button is clicked to give the impression that it is being pressed. However, I am looking to enhance the responsiveness of the page, so that the images also cha ...

Show the text of a link when it is selected using the tab key in a JavaScript event

Snippet: <a href="#about"> About <abbr title="The Little Taco Shop">About LTS</abbr></a> Show the text "About LTS" when the tab key is pressed on the keyboard. ...

"Can you provide guidance on displaying a form for a specific element based on its unique ID

I am trying to display the edit form when clicking on a specific image, but it is currently showing for all tasks. I need help in figuring out how to make it show only for one task. I attempted to use useState to change the boolean value "active" to show ...

Error: An unexpected TypeError occurred while attempting to fetch an array or collection from MongoDB Atlas

As a beginner in the world of Express and Mongoose, I am currently working on retrieving an object from MongoDB Atlas using Mongoose.Model for educational purposes. In CoursesModel.js, I have defined the schema for my collections and attempted to fetch it ...

What is the best way to create a regex pattern that can effectively split two consecutive mathematical operators ("/-", "*-") from a given string equation?

Struggling to convert a string equation into an array of numbers and operators, but having trouble getting it right. Here is the regex I've tried: Input: '1+2-33/45*78'.split(/([\+\-\*\/]+)/) Output: ["1", "+", "2", "- ...

Issue with showing multiple images on HTML page

I'm currently working on enhancing my webpage by enabling the upload of multiple images. However, I'm facing challenges in figuring out how to obtain a valid URL for the image source and to verify if the correct number of files have been uploaded ...

Error message encountered: "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, specifically occurring on the get request

Upon completing the construction of my project, I have encountered an error following the building of my application. The error message reads: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 This error only appears on pages ...

Invoking JavaScript function at set intervals of time

I am currently working on JavaScript code where I am trying to establish a connection with a remote asp.net page (aspx) using AJAX. My goal is to check this connection for a maximum of 2 minutes, with intervals of 10 seconds each. Here is the logic that I ...

What is the best way to create divs that can close and hide themselves when clicked from inside the div itself?

I have a situation in my code where clicking a link reveals a div, and then the same link must be clicked again to hide it. However, I want to modify this so that any link within the div can also hide it when clicked. I currently have eight divs set up lik ...

The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar. window.setInter ...

Grouping promises together using Promise.all

I came across this code snippet and need help understanding it: db.group.findOne({_id: id}).then((groupFound) => { var membersArray = groupFound.members; Promise.all(membersArray.map((member) => { return db .doneTod ...

Issue with data(): "Error: The property 'length' cannot be read because it is undefined" (Vue.js)

Hey, I'm new to Vue.js and I think I might have made a silly mistake because I just can't figure out why I'm getting this error. Can someone please help me out? Here's the code snippet I'm working with: const bootstrap = require(" ...

"Difficulties with Tribute Page Project on FreeCodeCamp: HTML and

I am currently working on a tribute page for a challenge from FCC and I am facing some issues with adding padding to my .life and .work divs in the HTML and CSS code above. Despite spending a few hours searching for solutions online, I have not been able ...

How to export HTML table information to Excel using JQuery and display a Save As dialog box

This script has been an absolute lifesaver for my web application. Huge thanks to sampopes for providing the solution on this specific thread. function exportToExcel() { var tab_text="<table border='2px'><tr bgcolor='#87AFC6& ...

Tips for refreshing Facebook's og tags

I've been racking my brains over this issue for days, and despite the abundance of similar inquiries, I have yet to find a solution. On my blog-like website, each post requires its own title and description for Facebook articles. I know I can set the ...

Instructions for rearranging the configuration of a 2D array?

A 2-dimensional array is created from a string called matrix: 131 673 234 103 018 201 096 342 965 150 630 803 746 422 111 537 699 497 121 956 805 732 524 037 331 After parsing, it becomes an array of arrays like this: [ [131, 673, 234, 103, 018], [2 ...