How do you make onlick fire for ONLY the "top-most" div?
Hey guys,
Let's say I've got 2 divs, A and B, and each div has a separate onclick event. Div "A" is in the background, and div "B" is in the foreground, like this...
What I want to do, is when div B is clicked on, it fires ONLY the onclick event for div B. But as it is, whenever I click on Div B, it fires the onclick event for Div B AND Div A.
So... how can I keep the div A onclick event from firing whenever I click on Div B?
From the code, when you click on div id=a it will call the function a(event) and alert "a", click on div id=b it will call the function b() and alert "b".
I put id=event.target.id in the function a() to get the id of the target element which got triggered. I then check such id If target id isn't "a" it will not do anything.
This is a much cleaner piece of code. For one it doesn't have inline scripting (scripting attached to the element) and secondly it'll work in every single browser.
You will also note that the event reserved word must be passed in to the function. If you remove it, this code will stop working in Firefox. The reason for this is simply that the event object is not a property of the window, so cannot be directly accessed from the function. Other browsers let you get away with it, but Firefox does not.
Bookmarks