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

Is it possible to execute this animation with a single click for repetitive playback?

CODEPEN const btt = document.querySelector('.btt'); btt.addEventListener('click', function(){ this.classList.toggle('anime'); }); Is there a way to achieve the desired effect with just one click? ...

Enhance the current menu item in WordPress by assigning a class to the anchor tag

function updateActiveClassOnMenu($item_output, $item, $depth, $args) { $menu_locations = get_nav_menu_locations(); if ($item->menu_order == 1){ $item_output = preg_replace('/<a /', '<a class="active" ', $item_o ...

Accessing a factory from within another in AngularJS Ionic

My Ionic app has been developed with two separate factories: one called Api, which handles API calls, and another called LDB (local database), responsible for interacting with a local Sqlite database using the CordovaSqlite plugin. While each factory work ...

The web service that retrieves XML data using jQuery functions perfectly on a local environment, but faces issues when deployed to

I have a webmethod that returns data. I am using jQuery to call this function with its Content type specified as XML. The interesting issue is that it works fine on my local machine but not on the server. Here is the code snippet I am currently using: var ...

Enhancing images by creating clickable sections in a more organized and efficient manner

Are there any other methods to make parts of an image clickable in a more organized way, aside from using the coordinates method or directly embedding images from Photoshop? <script> new el_teacher = ["candice","john"]; $(".teacher1").mouseenter(fu ...

The SVG animation is reversing and decreasing in size from the bottom

Feeling lost, I spent a day searching without success. I have a project in full Vuejs and I thought using Svg would be easy and fun, but I can't figure out why the image resizes when playing an animation. The bottom of the svg seems to resize and get ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

Having trouble processing the Firebase snapshot with Node.js

I have a question regarding a snapshot; ref.orderByChild("index").equalTo(currentIndex).once("value", function(snapshot) {}) After printing the snapshot with ; console.log(snapshot.val()); This is the output that gets printed; {'-LBHEpgffPTQnxWIT ...

Leveraging the power of ajax to securely save information in a database with the web2py framework

Struggling with a major issue here. I have set up the following tables db.define_table('post', Field('user_email', default=auth.user.email if auth.user_id else None), Field('title', 'strin ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Detecting key press events with extended duration using the DOM keydown event

Is there a way to receive notification when a key is pressed down, but not until it is released? It seems that using keydown continuously triggers the onkeydown callback while the key is held down. ...

The font-size transition using CSS3 is experiencing a lack of smoothness specifically in the

I have crafted a simple animation for an h1 element, utilizing css3 and a transition on the font-size. Here is the link to view: http://jsbin.com/oPIQoyoT/1/edit h1 { position: relative; width:500px; height: 500px; font-size: 3em; tra ...

Encountering the error "undefined object" while using the yield keyword in JavaScript

var pi = document.getElementById("pi"); function * calculatePi(){ let q = 1; let r = 0; let t = 1; let k = 1; let n = 3; let l = 3; while (true){ if (4*q+r-t < n*t){ alert(n); yield n; ...

Is it possible to receive both errors and warnings for the same ESLint rule?

My team is currently in the process of refactoring our codebase, utilizing ESLint to pinpoint any lint errors within our files. Initially, we set high thresholds in one .eslintrc file and have been gradually decreasing these limits as we enhance specific f ...

Group records in MongoDB by either (id1, id2) or (id2, id1)

Creating a messaging system with MongoDB, I have designed the message schema as follows: Message Schema: { senderId: ObjectId, receiverId: ObjectId createdAt: Date } My goal is to showcase all message exchanges between a user and other users ...

Explore Youtube to find the most popular video IDs

Is it possible for me to use a string to search YouTube and retrieve the id for the top video in the search results? I want to be able to play that video directly on my website. All I have is the URL for the search: youtube_url/results?search_query=thevid ...

What is the advantage of utilizing the ng-idle library for monitoring user idle status when we have the ability to create custom JavaScript code to track inactivity based on keyboard and mouse events?

I have implemented a method to detect user idle time using mouse and key events as shown below. @HostListener('window:keydown', ['$event']) @HostListener('window:mousedown', ['$event']) @HostListener('window:mou ...

When attempting to input data into the database, an error is displayed stating that /test.php cannot be POSTed

Every time I try to input data using PHP, it throws an error Cannot POST /test.php. I've been attempting to fix it with no success. Can anyone please help me solve this issue? It's crucial for my project work. Here is my HTML code: <html> ...

Updating the state of a nested array using React Hooks

After spending some time working with React Hooks, my main struggle has been dealing with arrays. Currently, I am developing a registration form for teams. Each team consists of a list of players (an array of strings). The goal is to allow users to add t ...

Animating scrollTop using JQuery

There are two buttons with hidden parts related to each. When a button is clicked, its associated part will be displayed and the document will scroll to the top. Issue: The displayed part does not move to the top as intended. Your assistance in resolving ...