Elias Zamaria
Elias Zamaria

Reputation: 101063

Strange behavior in IE when combining click handler with CSS sibling selector

I am trying to design a menu that is triggered by clicking a button. When the user clicks the button, a click handler runs which adds a class to the button, and a CSS rule using an sibling selector makes the menu visible. It works fine in all the browsers I tested except IE 7 and 8.

In IE 7 and 8, I am experiencing these problems:

  1. Clicking the button toggles the class but the menu doesn't appear or disappear until I move the mouse around a little bit.
  2. The menu doesn't work at all unless I have a CSS :hover declaration for children of the menu. It doesn't matter what I put in the declaration, or if I put anything at all, but the menu does not show up without it.

Can anyone tell me why this is happening and what I can do about it? I was thinking of adding a separate class to the menu but I am wondering if there is a simpler fix or workaround. Here is my code:

<!DOCTYPE html>
<html><head>
<title>IE selector test</title>
<style type="text/css">
button {
  border: outset 1px #eeeeee;
}
button.active {
  border-style: inset;
}
.menu {
  display: none;
  border: solid 1px #888888;
}
button.active ~ .menu {
  display: block;
}
.menu > :hover {
  /* For some reason, the menu doesn't work at all without this declaration */
}
</style>
</head>
<body>
<button type="button" id="menuButton">Menu</button>
<div class="menu">
  <div>option</div>
</div>
<script>
document.getElementById("menuButton").onclick = function() {
  if (this.className) {
    this.className = "";
  } else {
    this.className = "active";
  }
};
</script>
</body>
</html>

You can also test it at http://jsfiddle.net/QKqpn/.

Upvotes: 0

Views: 297

Answers (1)

Marat Tanalin
Marat Tanalin

Reputation: 14123

You can work around it by forcing page redraw:

document.body.className = document.body.className;

See http://jsfiddle.net/uGW4M/

BTW, in your case you can use + (one immediate sibling) combinator instead of more common ~ (all subsequent siblings):

button.active + .menu {/* ... */}

Upvotes: 2

Related Questions