Conceal navigation options post selection

I have successfully created a navigation menu, but I am facing an issue where the menu remains open until the mouse moves out of the dropdown.

I already have a function in place that displays content in another <div> (otherDiv) when an item is selected from the menu. Now, I want this function to also hide the menu simultaneously.

function go(obj) {
  var page = obj.href;
  document.getElementById('otherDiv').innerHTML = '<img src="' + page + '"></img>'
  return false;
  document.getElementById('menu1').style.display = "none";
  document.getElementById('menu2').style.display = "none";
  document.getElementById('menu3').style.display = "none";
  document.getElementById('menu4').style.display = "none";
  document.getElementById('menu5').style.display = "none";
  document.getElementById('menu6').style.display = "none";
}
    .drpbtn {
display: inline-block;
color: #ffffff;
text-align: center;
padding: 12px 25px;
list-style-type: none;
width: auto;
margin: 0;
background-color: #403e3e;
color: #ffffff;
float: left;
font-family: arial;
font-size: 14px;
}

.drpbtn:hover {
background-color: #00b3be;
}

.drpbtn:hover .dropdown-content {
display: inline-block;
}

.dropdown-content {
display: none;
list-style-type: none;
position: absolute;
background-color: #fafafa;
width: 290px;
color: #000000;
text-align: left;
margin-left: -4.7em;
margin-top: 0.89em;
}

.dropdown-content li:hover {
background-color: #e1e1e1;
}

.dropdown-content li {
display: block;
}

.li-drop {
display: inline-block;
color: #000000;
text-align: left;
padding: 11px 13px;
text-decoration: none;
margin: auto;
}   
<div id="menu">
  <ul>
    <li class="drpbtn">Menu 1
      <ul id="menu1">
        <div class="dropdown-content">
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 1</div>
            </a>
          </li>
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 2</div>
            </a>
          </li>
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 3</div>
            </a>
          </li>
        </div>
      </ul>
    </li>
    <li class="drpbtn">Menu 2
      <ul id="menu2">
        <div class="dropdown-content">
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 1</div>
            </a>
          </li>
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 2</div>
            </a>
          </li>
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 3</div>
            </a>
          </li>
        </div>
      </ul>
    </li>
    <li class="drpbtn">Menu 3
      <ul id="menu3">
        <div class="dropdown-content">
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 1</div>
            </a>
          </li>
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 2</div>
            </a>
          </li>
          <li class="li-drop">
            <a href="url" onclick="return go(this);">
              <div class="div-drop">Choice 3</div>
            </a>
          </li>
        </div>
      </ul>
    </li>
  </ul>
</div>

I need assistance with resolving this issue. Can you help?

Answer №1

function clickHandler(element) {
  var link = element.href;
  document.getElementById('imageContainer').innerHTML = '<img src="' + link + '"></img>'
  hideMenuItems();
  return false;
}

It seems like your return statement is misplaced in the code snippet you provided. Moving it to the end of the function ensures that all necessary operations are completed before exiting the function. Revised version of your code is shown above for reference.

Answer №2

Here's a jquery example showing how to hide a navigation menu after a single click outside of the menu. Simply assign a class="menu" to your <div> element with id="menu", test out the code, and adjust it to fit your specific requirements based on parent class names.

<script>
    $(document).click(function (e) {
        var $e = $(e.target);
        if (!$e.parents().hasClass('menu')) {
           $('.menu').css({ 'display': 'none' });
        }
    });
</script>

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

How do I transition this promise from deferred style to ES6 style in JavaScript?

Make sure to take a look at Rookie mistake #4: using "deferred" in Nolan Lawson's insightful article titled We have a problem with promises (which is definitely worth the read). I used to rely on deferred style promises, but after reading this, I&apos ...

Determine the full location information with the help of Google Maps SDK without the need

My current challenge involves dealing with a list of unformatted and incorrectly written addresses. I am seeking a way to iterate through these flawed strings and generate more organized and accurate addresses using one of the many Google Maps SDKs availa ...

Keep the animation keyframes looping endlessly

I am creating a countdown timer circle. The animation functions properly on the initial iteration, however, the circle animation remains full after the first iteration and does not reset. Despite this, the countdown number continues to function correctly, ...

Multiple individual image uploads via ajax on a single webpage

Currently, I am facing an issue with my ajax upload script. It only allows for one image upload at a time which is causing problems for me as I am working on a shop CMS that requires multiple image uploads for each product. Each product needs a thumbnail i ...

Is there a way to extract an object id from JSON data in Javascript?

I'm currently utilizing the Alpha Vantage API for retrieving stock market information. All data is provided in a specific format: To visualize this data effectively, I need to compile an array or object containing all the dates. Unfortunately, these ...

Flex - offspring locked in place and filling the full height

I need a menu that stays fixed at a height of 100, stretching to accommodate its content. If the content exceeds the height of the menu, a scrollbar should appear within the menu without allowing it to grow beyond 100. The page's content, on the othe ...

Align the positioning of the dropdown menu and the input field

I'm having trouble with css and ng2-completer. I am attempting to line up the dropdown section with the input field. Unfortunately, there is no demo example provided on the page showing how to target elements using css. I've tried selecting the ...

What is the best way to incorporate AJAX with Node.js?

After testing the Hello world program with Node.js, I can confirm that it is working perfectly. Here are the file details: index.html socket.js To run in command prompt: node socket.js I also experimented with ajax calls in Node.js using the same hel ...

Changing JSON names to display on a webpage

I am looking to modify the name displayed in a json file for presentation on a page using ion-select. mycodehtml ion-select [(ngModel)]="refine" (ionChange)="optionsFn(item, i);" > <ion-option [value]="item" *ngFor="let item of totalfilter ...

Trouble retrieving information from cloud function through https callable connection

I've encountered an issue with my Angular application where the value returned from a cloud function is always null, despite the fact that the cloud function logs the correct result. I'm unsure of what mistake I might be making. My Angular code ...

Generate a list of various clocks by clicking a button with the help of Javascript

Allowing the user to select a timezone from a dropdown and display the time seems simple enough. However, I also want users to have the ability to add multiple clocks for different timezones. I've encountered two conflicting problems: I can add clock ...

Is there a way to automatically initiate the download of a file (such as a PDF) when a webpage loads?

Currently, my objective is to have a form on a webpage that, once filled out by a user, redirects them to a thank you page where a message of gratitude is displayed. What I aim to accomplish is for a PDF file to automatically start downloading as soon as t ...

Navigating a Mesh in 3D Space using three.js, Camera Movement, and physi.js

I am attempting to manipulate an object in Three.js using Physi.js. The camera is linked to the moving mesh, and I am moving it using .setLinearVelocity(); Additionally, I rotate it using .setAngularVelocity(); However, the issue I am facing is that whil ...

Is it possible for an Express app.get() function to identify and handle requests for specific file extensions

Is it possible for me to manage requests for any .html file type? For example, can I achieve something like this: // server.js app.get('/*.html', (req, res) => { // perform certain actions when an html file request is made }); ...

Scanning through a directory to find fragments of a file's title

Currently, I am in the process of creating a media viewing platform that automatically downloads new episodes of TV shows. One obstacle I have encountered is the need to specify a source for the video content, as each episode download has a unique naming ...

Tips on incorporating an external JSON file into a javascript variable for global accessibility

I have been utilizing a JSON file in my project with the following structure: <script src="js/main.js"></script> <script> var data = {"bills":[{"id":1,"name":"DStv","reference":"SmartCard Number","logo":"bill\/logo\/24 ...

The inline style fails to take effect on input elements that are generated dynamically

Consider: $( "#scanInDialogItems tr td:nth-child( 3 )").mouseenter( function() { var q = $( this ).html(); $( this ).html( "<input type='number' style='text-align:right width:50px' min='1' value='" + q + " ...

Attempting to extract information from paginated asp pages using Scrapy Splash in the Python programming language

I am currently working on a project that involves using scrapy and splash to extract information such as Staff, job titles, and emails from a specific website's staff page. Here is the link to the page: . Due to the presence of dynamic javascript code ...

Creating a dynamic dropdown menu using JQuery that does not automatically submit the form when a value is

Upon selecting a background color from the dropdown menu, I am generating a dynamic dropdown for text colors. The Text Color dropdown is populated correctly based on the selection of Background Color. Although the functionality works as intended, I encoun ...

Getting a ThreeJS element, specifically a mesh, by its ID

I am working with a Mesh object in Three.JS. Is there a way to retrieve the Mesh object by its id and adjust its position, similar to using $(#"sample") in jQuery? Alternatively, do you have any suggestions for changing the position of objects in the ...