tyebillion tyebillion - 9 months ago 79
CSS Question

Drop down menu works well in Firefox but not reliably in Chrome

I have a drop down menu using JavaScript. It works reliably in Firefox (version 57). However, in Chrome (version 62) the drop menu only appears if you first click elsewhere on the page, and then on the menu icon / button. I am using 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 Source

I've tested the code provided in Chrome 62 and Firefox 57. I cannot reproduce your described behavior:

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

There is, however, an issue when you click the <img> inside the <button> which is caused by the <img> being the event target in Chrome. You can solve this by changing your condition to check if #button is the target itself or the parent node of the target.

So change 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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download