The dropdown menu functions smoothly in Firefox, although it may be less consistent in Chrome

I am encountering an issue with my JavaScript drop down menu. It functions properly in Firefox (version 57), but in Chrome (version 62) the drop-down only appears after clicking elsewhere on the page before clicking on the menu icon or button. My code includes jQuery 3.2.1 and Bootstrap 2.3.2.

var shown;

$(function() {
  shown = false;
});

window.onclick = function(event) {
  if (event.target.id == "button") {
    if (shown)
      $("#dropdown").hide();
    else
      $("#dropdown").show();
    shown = !shown;
  } else if (shown) {
    $("#dropdown").hide();
    shown = false;
  }
}
.dropdown {
  display: none;
  float: right;
  right: 0;
  margin-right: 7px;
  position: absolute;
  z-index: 1;
}

.dropdown a {
  padding: 12px 16px;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="icon">
  <button id="button">
    <img src="cogwheel.png">
  </button>
  <div id="dropdown" class="dropdown">
    <a href="todo2">Register</a>
    <a href="todo1">Login</a>
  </div>
</div>

Answer №1

After testing the code in both Chrome 62 and Firefox 57, it seems that the described behavior cannot be reproduced:

"...in Chrome (version 62) the drop menu only appears if you first click elsewhere on the page, and then on the menu icon/button"

One issue identified is when clicking the <img> inside the <button>, as this causes the <img> to be the event target in Chrome. This can be resolved by adjusting the condition to check if #button is the target itself or its parent node.

Therefore, modify if (event.target.id == "button") to

if (event.target.id == "button" || event.target.parentNode.id == "button")
.

var shown;

$(function() {
  shown = false;
});

window.onclick = function(event) {
  if (event.target.id == "button" || event.target.parentNode.id == "button") {
    if (shown)
      $("#dropdown").hide();
    else
      $("#dropdown").show();
    shown = !shown;
  } else if (shown) {
    $("#dropdown").hide();
    shown = false;
  }
}
.dropdown {
  display: none;
  float: right;
  right: 0;
  margin-right: 7px;
  position: absolute;
  z-index: 1;
}

.dropdown a {
  padding: 12px 16px;
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="icon">
  <button id="button">
    <img src="cogwheel.png">
  </button>
  <div id="dropdown" class="dropdown">
    <a href="todo2">Register</a>
    <a href="todo1">Login</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

Issues identified with High Charts functionality

I visited a helpful link to learn how to create bar graphs using the HighCharts Charting library. While it works perfectly on jsfiddle, I encountered an issue when trying to build an HTML file with the code as it doesn't display anything. Below is m ...

Is there a way to prevent a tag from being clickable on the entire row, except for the actual link itself?

My question is why, when using the a tag, the entire row on the right becomes clickable as well? Despite there being no link, the area at the back of the row on the right side is clickable. Is there any way to remove this clickable area? <a id="ba ...

Arrange the objects in the array according to the specified items that should come after

Consider the following data structure: var set = [ { "name":"alpha", "require":[] }, { "name":"beta", "require":["echo"] }, { "name":"charlie", "require":[] }, { "name":"d ...

Unexpected CSS Error in Visual Studio Code

<p I'm currently learning CSS and running into some errors on Visual Studio Code, even though my code is functioning correctly. I've attempted to troubleshoot by removing extensions but with no success. Any advice or assistance would be greatl ...

Transform the JSON structure with the power of JavaScript

Seeking assistance in converting the following array of JSON using either javascript or jquery: [ [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":48,"day7":154,"name":"Packet"}], [{"day1":10,"day2":154,"day3":24,"day4":48,"day5":154,"day6":4 ...

How to align icon and text perfectly in a Bootstrap 5 Button

I am looking to align icons and text within a modal body: <div class="modal-body"> <div class="d-grid gap-2" id="someButtons"> </div> </div> This code snippet demonstrates how I insert buttons ...

In NextJS 12, an UnhandledPromiseRejectionWarning occurs when trying to reference the TextEncoder which is not defined

Currently, I am working on developing a Spotify clone using NextJS 12 along with a Tailwind CSS template. To initiate the project, I executed the following command: npx create-next-app -e with-tailwindcss spotify-2. The project was successfully created, b ...

The integration of the jQuery library within the server side of a Google Apps Container Bound Script

Can the jQuery library be utilized server-side in a Google Apps Script that is Container Bound to a Doc or Sheet? If so, what steps should be taken? In a previous inquiry on Stack Overflow, I sought guidance on incorporating jQuery into a container-bound ...

Discover the method for populating Select2 dropdown with AJAX-loaded results

I have a basic select2 box that displays a dropdown menu. Now, I am looking for the most effective method to refresh the dropdown menu every time the select menu is opened by using the results of an AJAX call. The ajax call will yield: <option value=1 ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Converting a JavaScript map into an array with ES6: A step-by-step guide

I am in need of a solution to convert a JavaScript map into an array with a specific format: [ { name: "21 years old", totalUsers: 2, }, ... ] For example, if I have the following map: const ages = { "21": 2, "18 ...

The Chrome Dev Tools console displays the letter "f" instead of the actual values contained in the array - JavaScript

Currently diving into the world of JavaScript and embarking on a journey with Stack Overflow (enrolled in a JavaScript Udemy course as well). During an exercise involving arrays, I found that the Chrome Dev console was only displaying [f, f, f, f] along wi ...

In the world of web development with JavaScript, jQuery, and EasyUI, we often encounter situations where the parameter

function formatData_original() { // convert obj_num2.formatter = function(value, rec) { var baseStr='&nbsp;&nbsp;' + rec.s_date + '<a class="easyui-linkbutton" href="javascript:void(0);" plain= ...

How can JavaScript be properly embedded using PhantomJS?

My objective is to insert the following code snippet into a website using PhantomJS: javascript document.getElementById("pickupZip").value = "90049"; document.getElementById("refreshStoresForZipPop").click(); After attempting this in my inject.js file, I ...

The rules for prioritizing CSS selectors

Struggling with CSS selector rules and specificity? I've already checked this for specifics. Even tried using firebug and inspecting elements in Chrome to copy the CSS path, but still can't get it to work. This is my first time creating a website ...

remove an element from a nested array using MongoDB

Greetings everyone! I am currently working on a materials document that contains arrays of articles, each article having an array of details. Here is a snippet from my collection data: { "_id": "62f2404b42556d62e2939466", "code&quo ...

Converting bullet point list to checkboxes once requirements have been satisfied

I am working on developing a password validator with specific regex conditions in Material UI that transitions from bullet points to checkboxes when the criteria are satisfied. https://i.sstatic.net/b0pgb.png Initially, I attempted to use the npm library ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

Facing an issue with Axios in React Native where I am unable to POST a Blob or File

After capturing an image with react-native-image-picker, I am attempting to upload the raw data of the picture using Axios. I managed to create a blob by fetching the image URI and converting it like so: const file = await fetch(response.uri); const theBl ...

Choosing a value from an HTML5 datalist using Selenium

When attempting to choose from a datalist, I am encountering an issue where only the first element in the list is selectable. Below is an example of the HTML snippet: <td> <input id="applianceFilterTextbox" class="flat" name="applianceFilter" li ...