I have a silly (and hopefully easily fixed) problem, which I will now attempt to describe.
The scenario-> I am trying to create a context menu using HTML / CSS / JS. Just a DIV with a high z-order that appears where a user right-clicks. Simple, and that portion works. The portion which does not is my attempt to make the menu disappear if the user clicks somewhere where a context menu is not supported; I am attempting to achieve this end with a general function in the BODY tag that fires onclick. Since the BODY tag is given a z-order of -1, and any other tags which might trigger the context menu to appear are given a higher z-order value, my hope was that if I right-clicked an element with a z-order of, say, 3, then it would fire the showMenu() function; instead, it appears that it does this, as well as passes the event to the underlying BODY tag, which causes the menu to become hidden again.
As you might imagine, it is incredibly frustrating. Does anyone know how to make prevent events from being passed down? (The INPUT button is what you may want to look at, the A anchor is something similar, but not coded to work just yet).
Here’s the HTML code:
And here’s my CSS file:
This appears to be a problem with IE, Firefox, and Chrome.
A lot of DOM events “bubble” from the bottom object up through container objects, which means they’ll eventually reach the body. But you can stop this – try adding the following code to the click handler on your element:
…where
eis the variable you already have in your function representing the event object.event.stopPropagation();should work in modern browsers, but the old IE way wasevent.cancelBubble = true;– to be safe you can just do both (but as shown above check that.stopPropagationis defined before trying to call it).With the above code added, if you click on the element your function will stop container objects (include the body) from seeing the click. If you click somewhere else your function isn’t called so then the body will process the click.
There’s more info about this at MDN and QuirksMode.org.
Note: I’ve ignored the z-order issue because in this case I think it is a non-issue – all elements are descendents of the body so (unless you stop it) I would expect events to bubble to the body regardless of z-order.