Finishing a division by both clicking outside of it and pressing a button

I am currently working on setting up a dropdown menu that can be closed both by clicking outside the opened div and by clicking the button or image that opens the div.

Image with onclick function:

<img onclick="hide()" id="menu" src="....">

The dropdown list that should be opened and closed is defined with the class display:none:

<ul id="dropdown" class="dropdown-breadcrumb">
       <li>...</li>
    </ul>

This is what I have come up with so far:

function hide() {
        var x = document.getElementById("dropdown");

        if (x.style.display === "none") {
            x.style.display = "block";
        } else {
            x.style.display = "none";
        }
    }

Now, when I try to add a function that closes the dropdown when the user clicks outside of it:

window.addEventListener('mouseup', function(event){
            var dropd = document.getElementById('dropdown');

            if(event.target != dropd && event.target.parentNode != dropd){
                dropd.style.display = 'none';
            }
    });

I am facing an issue with the dropdown staying open because the onclick function is triggered. Can anyone assist me in combining these functions? Thank you!

Answer №1

To better organize your code and handle the visibility of elements, you can centralize all your logic within the click listener function:

window.addEventListener('mousedown', function(event) {
  var dropd = document.getElementById('dropdown');
  var img = document.getElementById('menu');

  if (event.target === img && dropd.style.display === "none") {
    dropd.style.display = "block";
  } else if (event.target != dropd && event.target.parentNode != dropd) {
    dropd.style.display = 'none';
  }
});
<img id="menu" alt="img" />
<ul id="dropdown" class="dropdown-breadcrumb" style="width: 40px;">
  <li>First</li>
  <li>Second</li>
</ul>

Answer №2

Here is another option you could explore.

  $(window).click(function() { //Hide the menus if they are currently visible });

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

In order for Angular forms to be considered valid, they must fall into one of two form

I am attempting to create a dynamic angular form where the user must enter either A or B. A represents a unique identifier, while B consists of a set of values that correspond to that identifier. My goal is to validate the form as valid if either A is ente ...

Tips for obtaining latency measurements from the DailyMotion player during a live video stream

Is there a way to determine the latency of DailyMotion live video for synchronization with events, such as displaying speaker names alongside the video? I have been utilizing the DailyMotion player API in JavaScript but haven't found any information r ...

The Angular scope fails to reflect changes on the view

In this angular ng-click event, I have the following code: eventApp.controller('DetailEventController', ['$scope', '$http', '$compile', '$timeout', function ($scope, $http, $compile, $timeout, uiCalendarCon ...

Css beforehand, unique subject matter

Trying to use a jQuery plugin that has CSS code like this: .icon-eye:before { content: '\56'; } On the plugin's site, it displays as an eye icon. However, when I install the plugin on my local PC, I see 'V' instead of the ey ...

Should the value exceed the designated width of the combobox, it should be displayed across multiple lines

Having an issue where, when I set the width of the combobox and the value inside it is longer than expected, the full value isn't displayed. I am considering displaying the value on multiple lines to ensure the entire content is visible. Unfortunatel ...

Using JavaScript's regular expressions to identify a code block that commences with a specified pattern

Currently, I am working on a JavaScript script and I am in need of a Regex pattern to quickly match "JSDocs". The specific pattern that I am trying to match looks like this: # this is block1 /// text /// text /// text /// text # this is block2 /// text // ...

python conducting automation tests with Selenium WebDriver on a mouse

Hello, I'm having trouble with opening the Mouser website and using the search bar to send some data. Below is a sample of the code I've been working on, but I can't seem to find the correct CSS selector. Any help would be greatly appreciate ...

What is the best way to mock a Typescript interface or type definition?

In my current project, I am working with Typescript on an AngularJS 1.X application. I make use of various Javascript libraries for different functionalities. While unit testing my code, I am interested in stubbing some dependencies using the Typings (inte ...

Adjusting the timeout for a particular operation according to its unique identifier

I am looking for a solution to call a method that posts an answer after an input change in my Angular project. I want to reset the timeout if another input change occurs to avoid multiple posts. Is there a smart way to achieve this? My project involves po ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

Alignment of React page gets messed up upon inclusion of Gallery component

I have searched for solutions online, but nothing seems to work for me. I am facing an issue with my webpage that has multiple sections, and I want to display them one after the other vertically. Here is the code snippet: import React from 'react&ap ...

Retrieve a JavaScript object based on a specific value

Looking at my object : TeamMember = { 0 : {"ID": 100, "Name": "MNO", "Role": 2}, 1 : {"ID": 101, "Name": "PQR", "Role": 3}, 2 : {"ID": 103, "Name": "STU", "Role": 3} } I am trying to retrieve TeamMember[1] : {"ID": 101, "Name": "PQR", "Role": 3} a ...

Why do ES6 classes fail to set properties when an overloaded function is called within the constructor of the parent class?

I encountered a puzzling scenario while coding that has left me perplexed. Here's the situation: I am extending a class from a library, which serves as the "Parent"-class. It allows its subclasses to override the init-method for custom initialization ...

How to showcase base64 encoded images in pug (jade) with node.js

Can anyone help with decoding this mysterious data and displaying the image? I'm using pug as my template engine. Below is the questionable data that needs to be shown as an image: /9j/4AAQSkZJRgABAQEAYABgAAD/4QBaRXhpZgAATU0AKgAAAAgABQ ...and so f ...

Utilizing Java to Parse JSON Data with the JQuery Querybuilder | Discover more at http://querybuilder.js.org/

My goal is to develop a user interface for creating boolean expressions, and I have decided to utilize the JQuery QueryBuilder plugin/framework for this purpose. This tool provides me with JSON data representing the query generated in the UI. Now, I am lo ...

End all occurrences of XMLHttpRequest

In my code, I am calling the function SigWebRefresh at specific intervals of 50 milliseconds. tmr = setInterval(SigWebRefresh, 50); The function SigWebRefresh utilizes XMLHTTPRequest: function SigWebRefresh(){ xhr2 = new XMLHttpRequest(); ...

What is the best way to implement onChange for multiple form fields in Reactjs?

Can anyone help me troubleshoot my form? I'm having issues with typing into the fields and nothing happens when I try. Initially, whatever text I input would show up in all the fields simultaneously, but after making some changes, it stopped working ...

Having trouble spinning the picture using Reel in Reactjs

I have recently started learning React and I am attempting to use jQuery reel to rotate a list of images by 360 degrees. While I have successfully implemented this using purely jQuery, I now want to migrate it over to Reactjs. The issue arises when trying ...

Disable automatic focusing for a material-ui popover component

I am struggling to create a search match list that updates as the user types in their query. However, I am facing an issue where the input element loses focus to the pop-up. I have attempted to programmatically set the focus using refs, but I am unable to ...

Execute two tasks simultaneously in two separate workers utilizing the cluster module in node.js

I'm currently diving into clustering with NodeJS. My goal is to have two separate tasks - one handling node-sass and the other managing uglifyjs - each running on a distinct worker using cluster in NodeJS. The code I've implemented seems to be fu ...