How can we use JavaScript to close a dropdown menu when the user clicks outside of it?

I am facing an issue with my code. I want to close the dropdown menu when clicking outside of it or on the items within the dropdown. How can I achieve this?

I attempted to use

addEventListener('click', myFunction)
on `document` but it did not work as expected. I also looked for solutions on Stack Overflow, but most of them involved jQuery. Can someone help me fix this issue?

.block {
  display: block !important;
}
<div class="dropdown" style="position: relative;display: inline-block;">
  <button class="dropbtn" onclick="dropdown()" style="padding: 16px;font-size: 16px;border: none;cursor: pointer;">Dropdown</button>
  <div class="dropdown-content" id="dropdown" style="display: none;position: absolute;min-width: 160px;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);z-index: 1;">
    <a href="#" style="color: black;padding: 12px 16px;text-decoration: none;display: block;">Yes</a>
    <a href="#" style="color: black;padding: 12px 16px;text-decoration: none;display: block;">No</a>
  </div>
</div>
<script type="text/javascript">
  function dropdown() {
    document.getElementById("dropdown").classList.add("block");
  }
</script>

If I use the following code, the dropdown menu doesn't even open:

document.addEventListener("click", myFunction);
function myFunction(){
  document.getElementById("dropdown").classList.remove("block");
}

Thank you for your attention :)

Answer №1

Your approach will result in the closure of the app every time something on the document is clicked, which is not desired.

To prevent this, listen for the onclick event on the document but make sure to exclude the scenario when it is clicked inside your box:

.block {
  display: block !important;
}
<div class="dropdown" style="position: relative;display: inline-block;">
  <button class="dropbtn" onclick="dropdown()" style="padding: 16px;font-size: 16px;border: none;cursor: pointer;">Dropdown</button>
  <div class="dropdown-content" id="dropdown" style="display: none;position: absolute;min-width: 160px;box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);z-index: 1;">
    <a href="#" style="color: black;padding: 12px 16px;text-decoration: none;display: block;">Yes</a>
    <a href="#" style="color: black;padding: 12px 16px;text-decoration: none;display: block;">No</a>
  </div>
</div>
<script type="text/javascript">
  function dropdown() {  document.getElementById("dropdown").classList.add("block");
  }
  
  document.addEventListener("click", myFunction);
function myFunction(){
 if (!document.getElementsByClassName('dropdown')[0].contains(event.target)){ document.getElementById("dropdown").classList.remove("block");
 }
 }
 
</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

Safari is not properly rendering a React/Next.js website (showing a blank page)

Recently, I've been facing a frustrating bug on my Next.js website. When I try to open it in Safari, there's a 50/50 chance that it will either load correctly or show a blank page with faint outlines of components but no text. This issue occurs o ...

Having trouble loading select fields using AJAX within Wordpress? Update and find a solution!

UPDATE: I am struggling to iterate through the response object and populate a select field using my ajax function. Although I have tried using a for loop instead of each(), the select field gets populated with "undefined". Any suggestions on how to resolve ...

Guidelines for specifying alternate structures in JSON schema

I have two different JSON file structures, one like this: { "api": "http://my.api.host", "modules": [ "core", "module", "another" ] } and the other like this: { "api": "http://my.api.host", "modules": "*" } The modules attri ...

Guide on using javascript to alter a json structure

Recently, I discovered a method to manipulate a JSON file using JavaScript. Although I don't have any formal training in JavaScript, I understand that it is primarily utilized on web browsers. Can someone guide me on how to execute this script? I cons ...

The hover effect does not seem to be functioning properly within the <th>

I've been working on a tooltip feature that displays data in a message box when hovering over an icon based on its attribute. The following code is implemented for the mouseenter event. <span class='csTip fa fa-info-circle' csTipTerm=&a ...

Maintaining active navigation state in JQuery/JavaScript after clicking a link: tips and tricks

While many resources discuss adding the active class to a nav link using jquery, there is less information on maintaining the active state after the nav link has been clicked. After experimenting with code from various sources, I have attempted to set ses ...

Exploring the Differences Between Javascript Ajax Response and String Comparisons

I'm having trouble comparing the result of an ajax call with a string. The ajax call is returning the correct result, but I'm struggling to get the if statement to properly compare it with my string. Any suggestions on how to approach this? ...

The value entered is displaying as not defined

As a newcomer to the world of javascript, I am diving into creating a simple To Do list. The basic functionality is there, but I'm scratching my head trying to figure out why the input value in my code keeps returning undefined. The remove button is ...

Exploring the possibilities of reading and writing data in localStorage?

Just starting out with Phonegap, jQuery Mobile, and HTML5 - so please bear with me as I navigate through this learning process! I'm having an issue and could use some help. When trying to use a variable from localStorage, the screen remains blank whe ...

Please explain the concept of the Node.js event loop

I've spent countless hours poring over guides and resources on the event loop, yet I still can't grasp its essence. It's common knowledge that the libuv library is responsible for implementing the event loop, but what exactly is this entity ...

Using PHP to download a file

I have successfully uploaded a PDF file to a directory named 'documents' on my web server. Currently, I am populating a table with data from my database, and I want to create links in the forms column that directly link to the associated files w ...

Tips for applying a linear gradient mask to div elements?

I'm attempting to create a fading effect on the edges of a div by using two overlay divs positioned absolutely on either side. My goal is to have the background of the page visible once the fade is complete, effectively masking the content of one div ...

Recovering antiquated submission script in JavaScript

Here is a form with input data: <form id = 'myform'> ... <td><input type="checkbox" name="supplier_aid" value="on" checked disabled >{$output.t_artikelnr}</td> <td><input type="checkbox" n ...

Is there a way to populate two mysql tables using just one textarea input?

Hello, I'm currently working on my "Add Blog Post" page where I would like to make a change. Specifically, I want to eliminate one textarea (the post description area) and have the content entered in the Post Content textarea populate both the post de ...

Implementing a switch feature with enable/disable functionality in a material table using table row data

Is there a way to incorporate an additional action in the Material table and have it included in the React material table along with the element? Furthermore, how can I obtain row data on onChange event while currently rendering it in the state? I would a ...

What is the best way to list the choices associated with a specific category?

The Node.js package I'm currently working with requires an argument of a specific type, which I can see is defined through a TypeScript declaration as follows: export declare type ArgType = 'A' | 'B' | 'C'; I am interes ...

Challenges with xmlHttpRequest in a search autocomplete feature similar to Google's suggestion feature

I am currently working on implementing an autosuggestion search field that functions similarly to Google Suggestion. I am utilizing pure JavaScript/AJAX along with two files: index.php and ajax-submit.php (which is responsible for querying the database). H ...

Is there a way to extract video frames from a WebRTC local stream and transfer them to Python?

I am in the process of developing a video call application similar to Google Meet or Zoom, incorporating object detection using Python Flask or Django. Here is how the application functions: Users can join a channel for the video call The camera ini ...

How can I achieve a transparent background for a radio button in Chrome?

Today, I spent some time experimenting with the radio button to see if I could make its background transparent. I attempted the following CSS styling: input[type=radio] { background-color:transparent; background-image:none; -webkit-backface-v ...

Learn the art of generating multiple dynamic functions with return values and executing them concurrently

I am currently working on a project where I need to dynamically create multiple functions and run them in parallel. My starting point is an array that contains several strings, each of which will be used as input for the functions. The number of functions ...