JavaScript - The left dropdown menu stubbornly remains visible when clicked in white space, unlike the right dropdown which disappears as expected. Puzzled by this inconsistency

Whenever I click on the selection criteria box, a dropdown menu appears. Clicking on the white space or the data table button makes the drop-down menu disappear, which is good. However, when I perform the same action for 'choose data table,' the drop-down menu doesn't vanish unless I click on the button again. What could be causing this issue? I suspect it might be due to having identical code in both cases... If I remove the JavaScript code for the right-side window that allows the window to disappear upon clicking on the white space, the opposite occurs (the left box's menu disappears but not the right side). Full code provided below:

/* When the user clicks on the button, toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDatalist").classList.toggle("show")
}

window.onclick = function(event) {
  if (!event.target.matches('.dropdata')) {
    var dropdowns = document.getElementsByClassName("datalist-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

function criFunction() {
document.getElementById("myCriteria").classList.toggle("show")
}

window.onclick = function(event) {
  if (!event.target.matches('.dropcriteria')) {
    var dropdowns = document.getElementsByClassName("criterialist-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
} 
/*START Title*/

h1 { 
color: #46b3d1;
font-family: Gotham;
font-weight: 80;
 }

 /*END title*/

 /*START Database drop down*/
.dropdata {
font-family: Gotham;
    color: white;
    padding: 16px;
    font-size: 16px;
    width:200px;
    border: none;
    cursor: pointer;
    background-color: #46b3d1;
}


.dropdata:hover, .dropdata:focus {
    background-color: #22819b
}



.datalist {
    position: relative;
    display: inline-block;
    font-family: gotham;
}


.datalist-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    width:200px;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.datalist-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.datalist a:hover {background-color: #ddd;}
 /*END Database drop down*/


/*START Criteria box */

.dropcriteria {
font-family: Gotham;
    color: white;
    padding: 16px;
    font-size: 16px;
    width:200px;
    border: none;
    cursor: pointer;
    background-color: #46b3d1;
}


.dropcriteria:hover, .dropcriteria:focus {
    background-color: #22819b
}


.criterialist {
    position: relative;
    display: inline-block;
    font-family: gotham;
}


.criterialist-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    width:200px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.criterialist-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.criterialist a:hover {background-color: #ddd;}

.show {display: block;}


/*END Criteria box */
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Project Eric</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1>Project Eric</h1>

<div class="datalist">
<button onclick="myFunction()" class="dropdata">Choose data table</button>
<div id="myDatalist" class="datalist-content">
<a href="oxford_ann">Oxford Annual</a>
<a href="eng_counties">English Counties</a>
<a href="oxford_qu">Oxford Quarterly</a>
</div>
</div>

<div class="criterialist">
<button onclick="criFunction()" class="dropcriteria">Choose criteria</button>
<div id="myCriteria" class="criterialist-content">
<a href="index">Index</a>
<a href="database">Database</a>
<a href="filter">Filter</a>
</div>
</div>

Answer №1

There was an issue where only the first window.onclick function would trigger when a click occurred.

To fix this, merge the logic into a single method and it should function as intended.

/* Toggle between hiding and showing dropdown content when the user clicks on the button */
function myFunction() {
document.getElementById("myDatalist").classList.toggle("show")
}

window.onclick = function(event) {
  if (!event.target.matches('.dropcriteria')) {
    var dropdowns = document.getElementsByClassName("criterialist-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
  
  if (!event.target.matches('.dropdata')) {
    var dropdowns = document.getElementsByClassName("datalist-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
      var openDropdown = dropdowns[i];
      if (openDropdown.classList.contains('show')) {
        openDropdown.classList.remove('show');
      }
    }
  }
}

function criFunction() {
document.getElementById("myCriteria").classList.toggle("show")
}
/*START Title*/

h1 { 
color: #46b3d1;
font-family: Gotham;
font-weight: 80;
 }

 /*END title*/

 /*START Database drop down*/
.dropdata {
font-family: Gotham;
    color: white;
    padding: 16px;
    font-size: 16px;
    width:200px;
    border: none;
    cursor: pointer;
    background-color: #46b3d1;
}


.dropdata:hover, .dropdata:focus {
    background-color: #22819b
}



.datalist {
    position: relative;
    display: inline-block;
    font-family: gotham;
}


.datalist-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    width:200px;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.datalist-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.datalist a:hover {background-color: #ddd;}
 /*END Database drop down*/


/*START Criteria box */

.dropcriteria {
font-family: Gotham;
    color: white;
    padding: 16px;
    font-size: 16px;
    width:200px;
    border: none;
    cursor: pointer;
    background-color: #46b3d1;
}


.dropcriteria:hover, .dropcriteria:focus {
    background-color: #22819b
}


.criterialist {
    position: relative;
    display: inline-block;
    font-family: gotham;
}


.criterialist-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    width:200px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.criterialist-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.criterialist a:hover {background-color: #ddd;}

.show {display: block;}


/*END Criteria box */
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Project Eric</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1>Project Eric</h1>

<div class="datalist">
<button onclick="myFunction()" class="dropdata">Choose data table</button>
<div id="myDatalist" class="datalist-content">
<a href="oxford_ann">Oxford Annual</a>
<a href="eng_counties">English Counties</a>
<a href="oxford_qu">Oxford Quarterly</a>
</div>
</div>

<div class="criterialist">
<button onclick="criFunction()" class="dropcriteria">Choose criteria</button>
<div id="myCriteria" class="criterialist-content">
<a href="index">Index</a>
<a href="database">Database</a>
<a href="filter">Filter</a>
</div>
</div>

Answer №2

Just sharing some helpful information

function myFunction() {
document.getElementById("myDatalist").classList.toggle("show")
}

function criFunction() {
document.getElementById("myCriteria").classList.toggle("show")
}
window.onclick = function(event) {
var menus={
'dropdata':'datalist-content',
'dropcriteria':'criterialist-content'
};
for(var i in menus){
if(!event.target.classList.contains(i)){
var dropdowns = document.getElementsByClassName(menus[i]);
for(j = 0; j < dropdowns.length; j++){
if (dropdowns[j].classList.contains('show')) {
dropdowns[j].classList.remove('show');
}
}
}
}
}
h1 { 
color: #46b3d1;
font-family: Gotham;
font-weight: 80;
 }

 /*END title*/

 /*START Database drop down*/
.dropdata {
font-family: Gotham;
    color: white;
    padding: 16px;
    font-size: 16px;
    width:200px;
    border: none;
    cursor: pointer;
    background-color: #46b3d1;
}


.dropdata:hover, .dropdata:focus {
    background-color: #22819b
}



.datalist {
    position: relative;
    display: inline-block;
    font-family: gotham;
}


.datalist-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    width:200px;
    min-width: 160px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.datalist-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.datalist a:hover {background-color: #ddd;}
 /*END Database drop down*/


/*START Criteria box */

.dropcriteria {
font-family: Gotham;
    color: white;
    padding: 16px;
    font-size: 16px;
    width:200px;
    border: none;
    cursor: pointer;
    background-color: #46b3d1;
}


.dropcriteria:hover, .dropcriteria:focus {
    background-color: #22819b
}


.criterialist {
    position: relative;
    display: inline-block;
    font-family: gotham;
}


.criterialist-content {
    display: none;
    position: absolute;
    background-color: #f1f1f1;
    min-width: 160px;
    width:200px;
    overflow: auto;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
}

.criterialist-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
}

.criterialist a:hover {background-color: #ddd;}

.show {display: block;}


/*END Criteria box */
!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Project Eric</title>
</head>
<body>
<h1>Project Eric</h1>

<div class="datalist">
<button onclick="myFunction()" class="dropdata">Select data table</button>
<div id="myDatalist" class="datalist-content">
<a href="oxford_ann">Oxford Annual</a>
<a href="eng_counties">English Counties</a>
<a href="oxford_qu">Oxford Quarterly</a>
</div>
</div>

<div class="criterialist">
<button onclick="criFunction()" class="dropcriteria">Select criteria</button>
<div id="myCriteria" class="criterialist-content">
<a href="index">Index</a>
<a href="database">Database</a>
<a href="filter">Filter</a>
</div>
</div>

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

CarouFredSel Transition Troubles

I am currently using CarouFredSel to create an image carousel, but I am encountering some issues with the transitions between items. My goal is to incorporate simple HTML elements into the carousel instead of just plain images. However, when I attempt to ...

After refreshing in FireFox, the "disabled" attribute of the button fails to function

On my webpage, there are 2 buttons - one enabled by default and the other disabled. When I click on an enabled button, their states switch - the enabled button becomes disabled and vice versa. This functionality works perfectly in Chrome, Edge, and IE11, b ...

Is there a way to preserve the context in React when transitioning to a new page?

Currently, I am encountering a challenge within my React application involving multiple components, each utilizing its own context through the useContext hook. My goal is to uphold the context for each component even when there are changes in the URL. I a ...

Issue with mouseover in the jQuery area

As I navigate through a WordPress website, I am attempting to create a mandala using dynamic images. Utilizing jQuery and CSS areas, I aim to display the corresponding image when hovering over a specific section. However, I am facing an issue where there ...

Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex: posts:[ { id: 1; title: "Place", acf: { address: { state: "Arkansas", ...

Apple Automation: Extract a targeted string from text and transfer it to a different spot within the page

Apologies for my lack of expertise in this area, but I hope to convey my question clearly. I am working on a form where I need to input text in order to copy specific items and paste them elsewhere on the same webpage. For example, if the input text is " ...

How can I incorporate margins or adjust scaling within dompdf?

After creating a PDF using dompdf with the paper size set to A6, I am experiencing issues when trying to print it on A4 and letter paper sizes. The left and top borders are being cut off. Is there a way to generate a PDF that is compatible with A4, A6, l ...

How can you master the art of PHP templating like a pro?

Years ago, I started a small PHP website that has since grown into quite a mess. Despite having a separate template for the final HTML output, I still find myself handling a lot of HTML within the 'business logic' part of the code. My main issue ...

jQuery template does not respond to input text when a click event is enabled on an iPhone device

Below is a jQuery template I have: <div class="parent-class"> <div class="sub-class"> <div clas="sub-input-class"> <input type="text" /> </div> </div> </div> Recently, I ...

Changing the color of a menu item in Bootstrap when a modal window is closed: A guide

I am implementing Twitter Bootstrap and attempting to launch a modal popup by clicking on a menu item. Below is the code snippet: <div class="navbar navbar-fixed-bottom"> <div class="navbar-inner"> <ul class="nav pull-right"> ...

Is it possible to have a single listener for all events within the jQuery event namespace?

Is it possible to create a handler that can listen to ALL events within a specific namespace in jQuery using $.fn.on, off, and trigger functions? For example: $(window).on(".event_namespace", function(e){ //handler }); $(window).trigger("testEvent.e ...

Influencing location preferences in Google's place search

I'm currently implementing a Google Places search feature and I need to enable "Location Biasing" for the GCC countries (UAE, Saudi Arabia, Oman, Kuwait & Bahrain). My goal is to achieve the functionality described in the following link: https://deve ...

Show a checkbox element with a square in the center instead of a tick mark

Is there a way to create a custom checkbox in HTML with a black box in the center, similar to the third checkbox shown in the image below? I've noticed this design in many interfaces, but I haven't been able to find a satisfactory example online ...

Construct a table featuring nested rows for every parent entry

Table 1 orderid customerName totalCost ---------------------------------- 1 Jonh £200.00 2 Ringo £50 Table 2 orderlineid orderid productName productPrice Quantity ----------------------------------------------- ...

Is NextJS rendering solely on the server, or is it capable of rendering on both

Within my users.js JSX file, I have an exported component that looks like this: ... return <MainContainer keywords="users"> export default Users During the process of SSR/SSG, the browser displays the users HTML (comprising of <li> t ...

Utilizing environment variables in a Rails-AngularJS (1.5) project

Currently working on a Rails-AngularJS (1.5) project and encountering difficulties accessing my ENV variables in the JavaScript components such as services and console. I've implemented dotenv, stored my SECRET_KEY in a .env file, and included the fo ...

Adjust the size of a div while maintaining its aspect ratio based on the width and height of its parent element using CSS

After exploring various methods to create div aspect ratios using CSS, I had success with a demo. However, I encountered an issue with setting the height of my container when the width-to-height ratio is larger (#1 scenario). https://i.sstatic.net/VNdJ5.p ...

The JavaScript function for clearing an asp.net textbox is not functioning properly

I am working on an ASP.net project and have encountered an issue with two textboxes. When one textbox is clicked on, I want the other one to clear. Below is the code I have for the textboxes: <asp:TextBox runat="server" ID="box1" onfocus="clearBox2()" ...

The black package in package-lock.json seems to have a mind of its own, constantly disappearing and re

When running npm install, I've noticed that the property packages[""].name in the package-lock.json file is sometimes removed and sometimes added. How can I prevent this change from occurring, as it is causing unnecessary git changes? https ...

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...