Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening?

I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems:

1- Whenever I clicked on a menu item, an underline appeared for every item, which is not desired.

2 - After clicking on another part of the website, my menu completely disappeared and did not show up again, which is a major issue.

I want to implement click events or any related solution, but how can I resolve these issues? Your help in providing code directly would be highly appreciated, thank you.

The following code might help:

--- Add your own unique explanation or description here. ---

Answer №1

document.addEventListener('click', function(event) {
  if (event.target.closest('.nav')) {
    return;
  } else {
   document.querySelector('#subMenu').style.display = 'none';
   // Added an ID to the inner unordered list
  }
});

function toggle(element) {
  const nodes = getChildNodes(element.parentElement);
  if(nodes[1].style.display === 'block') {
    nodes[1].style.display = 'none';
  } else {
    nodes[1].style.display = 'block';
  }
}

function getChildNodes(node) {
  let children = new Array();
  for(const child in node.childNodes) {
    if(node.childNodes[child].nodeType == 1) {
      children.push(node.childNodes[child]);
    }
  }
  return children;
}
#ABT-Container  {
  font-family: 'Roboto', sans-serif;
  background: transparent;
  width:100%; float:right;
}

a {
  text-align: center;
  font-family: 'Roboto', sans-serif;
  color: #333;
}

.nav {
  float: right;
  font-family: 'Roboto', sans-serif;
  padding: 2px 6px 0;
  line-height: 100%;
  border-radius: 1em;
  background: white; /* For non-css3 browsers */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#FFFFFF'); /* For IE */
  background: -webkit-gradient(linear, right top, right bottom, from(#FFFFFF), to(#FFFFFF)); /* For webkit browsers */
  background: -moz-linear-gradient(top,  #FFFFFF,  #FFFFFF); /* For firefox 3.6+ */
  border: solid 1px white;
}

.nav .current a, .nav li:hover > a {
font-family: 'Roboto', sans-serif;
    background: white; /* For non-css3 browsers */
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#FFFFFF', endColorstr='#FFFFFF'); /* For IE */
    background: -webkit-gradient(linear, right top, right bottom, from(#FFFFFF), to(#FFFFFF)); /* For webkit browsers */
    background: -moz-linear-gradient(top,  #FFFFFF,  #FFFFFF); /* For Firefox 3.6+ */

    color: #444;
    border-top: solid 1px #FFFFFF;
    
}
/* Sub levels link hover */
.nav ul li:hover a, .nav li:hover li a {
font-family: 'Roboto', sans-serif;
    background: none;
    border: none;
    color: #666;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
}
.nav ul a:hover {
font-family: 'Roboto', sans-serif;
    background: #ff4718 !important; /* For non-css3 browsers */
    filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff4718', endColorstr='#FF0000'); /* For IE */
    background: -webkit-gradient(linear, right top, right bottom, from(#ff4718), to(#FF0000)) !important; /* For webkit browsers */
    background: -moz-linear-gradient(top,  #ff4718,  #FF0000) !important; /* For Firefox 3.6+ */

    color: #fff !important;
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    text-shadow: 0 1px 1px rgba(0, 0, 0, .1);
}


.nav li {
  font-family: 'Roboto', sans-serif;
  margin: 0 5px;
  padding: 0 0 8px;
  float: right;
  position: relative;
  list-style: none;
}

/* Main level link */
.nav a {
  font-family: 'Roboto', sans-serif;
  color: #353535;
  text-decoration: none;
  display: block;
  padding:  8px 20px;
  margin: 0;
  -webkit-border-radius: 0em;
  -moz-border-radius: 0em;
  text-shadow: 0 0px 0px rgba(0, 0, 0, .3);
}

/* Level 2 list */
.nav ul {
  font-family: 'Roboto', sans-serif;
  background: #FFFFFF; /* For non-css3 browsers */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#FFFFFF'); /* For IE */
  background: -webkit-gradient(linear, right top, right bottom, from(#fff), to(#FFFFFF)); /* For webkit browsers */
  background: -moz-linear-gradient(top,  #fff,  #FFFFFF); /* For Firefox 3.6+ */
  display: none;
  margin: 0;
  padding: 0;
  width: 185px;
  position: absolute;
  top: 35px;
  right: 0;
  -webkit-border-radius: 1px;
  -moz-border-radius: 1px;
  border-radius: 1px;
  -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
  -moz-box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
  box-shadow: 0 1px 1px rgba(0, 0, 0, .8);
}

/* Dropdown */
.nav ul li {
  font-family: 'Roboto', sans-serif;
  float: none;
  margin: 0;
  padding: 0;
}

.nav ul a {
  font-family: 'Roboto', sans-serif;
  font-weight: normal;
  text-shadow: 0 1px 1px rgba(255, 255, 255, .9);
}

/* Level 3+ list */
.nav ul ul {
  font-family: 'Roboto', sans-serif;
  right: 181px;
  top: -3px;
}

/* Rounded corners for first and last child */
.nav ul li:first-child > a {
  -webkit-border-top-right-radius: 1px;
  -moz-border-radius-topleft: 1px;
  -webkit-border-top-left-radius: 1px;
  -moz-border-radius-topright: 1px;
}

.nav ul li:last-child > a {
  -webkit-border-bottom-right-radius: 1px;
  -moz-border-radius-bottomleft: 1px;
  -webkit-border-bottom-left-radius: 1px;
  -moz-border-radius-bottomright: 1px;
}

/* Clearfix */
.nav:after {
  font-family: 'Roboto', sans-serif;
  content: ".";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
}

.nav {
  font-family: 'Roboto', sans-serif;
  display: inline-block;
}

html[xmlns] .nav {
  font-family: 'Roboto', sans-serif;
  display: block;
}

* html .nav {
  height: 1%;
}

.menu_line{
  width: 25px;
  height: 2px;
  background-color: black;
  color: black;
  margin: 4px 0;
}

.expand{font-size:24px;float: left;margin: 0px -5px;}

.menu_line{
width: 25px;
    height: 2px;
    background-color: black;
color: black;
    margin: 4px 0;
}
<nav id="bg1" class="navbar">
                
                  

                    <div id="ABT-Container">
                    <a href="index.html"><img src="img/new pic/Home.png" width="166" height="40"/></a>
    
    
    
    
<ul class="nav" id="dropdown"><li class="w3-animate-right"><a href="#" onclick="toggle(this)"><p class="menu_line"></p><p class="menu_line"></p><p class="menu_line"></p></a>
 <ul id="subMenu">
<li class="w3-animate-right"><a href="#" onclick="toggle(this)"><span class="expand">&#x25C2;</span>Our Technology</a>
 <ul>
<li class="w3-animate-right"><a href="#" onclick="toggle(this)"><span class="expand">&#x25C2;</span>Sub-Row</a>
 <ul>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row 1 clicked')">Sub Sub-Row 1</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row 1 clicked')">Sub Sub-Row 1</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row 1 clicked')">Sub Sub-Row 1</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row 1 clicked')">Sub Sub-Row 1</a></li>
</a></li></ul>
</li>
<li class="w3-animate-right"><a href="#" onclick="toggle(this)"><span class="expand">&#x25C2;</span>Sub-Row</a>
 <ul>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row 2 clicked')">Sub Sub-Row 2</a></li>
</ul>
</li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row clicked')">Sub-Row</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub Sub-Row clicked')">Sub-Row</a></li>
</ul>
</li>

<li class="w3-animate-right"><a href="#" onclick="toggle(this)"><span class="expand">&#x25C2;</span>Multi-Levels</a>
<ul id="dropdoswn">
<li class="w3-animate-right"><a href="#" onclick="console.log('Team clicked')">Team</a>
 <ul>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 1 clicked')">Sub-Level Item 1</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 1 clicked')">Sub-Level Item 1</a>
 <ul>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 11 clicked')">Sub-Level Item 11</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 22 clicked')">Sub-Level Item 22</a></li>
<li><a href="#" onclick="console.log('Sub-Level Item 33 clicked')">Sub-Level Item 33</a></li>
</ul>
</li>
                   
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 1 clicked')">Sub-Level Item 1</a></li>
</ul>
</li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Sales clicked')">Sales</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Another Link clicked')">Another Link</a></li>
<li class="w3-animate-right"><a href="#" onclick="toggle(this)"><span class="expand">&#x25C2;</span>Department</a>
 <ul>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 2 clicked')">Sub-Level Item 2</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 2 clicked')">Sub-Level Item 2</a></li>
<li class="w3-animate-right"><a href="#" onclick="console.log('Sub-Level Item 2 clicked')">Sub-Level Item 2</a></li>
</ul>
</li>
</ul>
</li><li class="w3-animate-right"><a href="#">Services</a></li>   
<li class="w3-animate-right"><a href="#">About US</a></li>
<li class="w3-animate-right"><a href="#">Contact US</a></li>
<li class="w3-animate-right"><a href="#">Our Links</a></li>
</li>
</ul>
</ul>
</ul>
</div>
                    <!-- Header Nav End -->
                    
            </nav>

Answer №2

This particular code snippet hides all div elements with the id="dropdown" (both parent and children) by setting their display property to none.

If you want to undo this effect, simply remove the following line of code:

document.querySelector('#dropdown').style.display = 'none';

Instead, consider using the toggle() function for a smoother transition.

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

Only forward if the page is accessed via jQuery

I am trying to make a page accessible only when it is dynamically loaded into another page using jQuery. If someone tries to access this page directly from the browser address bar, I want to redirect them. Can anyone advise me on how to achieve this? Appr ...

Node.js encountered an issue: Dependency 'mime-types/node_modules/mime-db' cannot be located

Recently, I followed a tutorial on creating a CRUD App with Nodejs and MongoDB. The project was completed successfully and everything was working fine. However, when I attempted to move all the files and folders to a new directory, disaster struck. Now, w ...

Can you explain the use of the 'this' keyword in map() and call() functions?

Recently, I've been revisiting my understanding of how to use call() and map() with a NodeList in JavaScript. It was quite easy to find information on how call() works, and there are plenty of examples of how it can be used with map(). However, whil ...

Populate the label text within a Gridview by parsing JSON data through AJAX

I am currently working with a grid view that obtains data from a vb.net class object. The gridview contains a TemplateField with a label control, as shown below: ...

What is the method to apply custom styles (CSS) to individual options within a jQuery UI selectmenu?

When working with an HTML form that includes a select element, I encountered a design challenge. <select id='myselect'> <option value='1'>1</option> <option value='2'>2</option> ... <option va ...

Can someone show me how to populate select options with values from a list using Python variables?

Instead of hardcoding values in my HTML file, I have a variable called 'myVariable' in my Python file that is a list. I want to use this variable to generate the options in my select menu. <select class="form-select" aria-label=" ...

Using asynchronous methods to import a Node.js module

I am attempting to asynchronously load 2 modules due to some issues I encountered. The first module loads and creates a database connection (which takes some time) The second module uses the created connection to handle sessions using express-sessions. ...

What is the best way to show a table with 100% width in the Chrome browser?

I am currently working on debugging and expanding an express application that showcases a dataset through a series of nested tables on a webpage. Initially, all the CSS resided within style tags in the head section of the HTML file, and the tables were dis ...

Await keyword cannot be used due to undefined object reference

Currently in the process of implementing authentication into my node API. Using PassportJS, although I am fairly new to this so please bear with me. The goal is to add a local strategy and verify the user's password during login: // Local Strategy ...

Error encountered with underscore template - Unforeseen SyntaxError: Unexpected token <

I encountered an error when attempting to load one of my underscore templates. It seems to be related to an issue in the for loop, which I suspect should be a .each loop, but I'm still trying to grasp its structure. Here is a snippet of my template: ...

Can jQuery be used to target pseudo elements such as scrollbars for selection?

Can you use jQuery to target pseudo elements like these: ::-webkit-scrollbar ::-webkit-scrollbar-track ::-webkit-scrollbar-thumb Is it possible to manipulate them through jQuery? #scroller { background: #fff; height: 300px; wid ...

Utilizing JQuery Ajax to dynamically replace elements using JQuery functions

My issue is as follows... I am using AJAX and jQuery to populate a form. When the user makes a selection from a dropdown menu, AJAX retrieves data based on the choice and populates the form with this data. Sometimes, new elements are created when the AJA ...

Loading external templates in Angular2 with Webpack2

Attempting to integrate ngtemplate-loader in a project using AngularJs 2 and Webpack 2 is proving challenging. While this setup has been successful in Angular 1.x projects with Webpack 1.x, it encounters an error when running in the browser: Uncaught Type ...

What is the best way to discover all available matches?

By utilizing this code snippet, I am able to locate text between specific start and end words. However, the search process stops after the first pair is found. Is there a way to identify all matches? const file = fs.readFileSync('./history.txt', ...

What are the steps to make the chosen title and its content active while deactivating the others?

I am currently developing a website for an educational institution that includes schools with subdivisions such as matric, CBSE, and state board, as well as a college. My goal is to create a user interface where clicking on a specific stream (such as matri ...

What is the best way to extract data from a series of nested JSON objects and insert it into a text field for editing?

I am facing a challenge with appending a group of nested JSON objects to a text field without hard coding multiple fields. Although I have used the .map functionality before, I am struggling to make it work in this specific scenario. const [questions, setQ ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

I need clarification on some basic concepts about ajax - Can you help?

Could someone please assist me in clarifying a concept? Currently, I am utilizing the colorbox plugin to load an external html snippet (which is functioning correctly). However, my jquery selectors are unable to detect the newly loaded html. Is this the co ...

the drawer conceals the paper

I am having an issue with my drawer overlapping the content on the page. I would like it to be aligned to the left without covering any other elements. This is my first time working with material-ui, so if anyone could help explain how to fix this, I wou ...

Determine if the value is present in every element of the array and return true

I am looking for a way to determine if all products have the status "Done" in their respective statusLog arrays. If any product does not contain "Done" or lacks the statusLog property altogether, then the function should return false. Although the current ...