Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make higher z-index elements disable lower elements' onclick

I've got a 'layer' that I want to give an onclick. The trick is that I want elements on above layers to not execute that action when clicked.

How can I make this happen?

Thanks!

like image 655
Nathan Avatar asked Mar 19 '11 18:03

Nathan


People also ask

How does a higher z-index value affect a positioned element?

The z-index property determines the stack level of an HTML element. The “stack level” refers to the element's position on the Z axis (as opposed to the X axis or Y axis). A higher value means the element will be closer to the top of the stacking order. This stacking order runs perpendicular to the display, or viewport.

What is Z-Index 9999?

In CSS code bases, you'll often see z-index values of 999, 9999 or 99999. This is a perhaps lazy way to ensure that the element is always on top. It can lead to problems down the road when multiple elements need to be on top.


1 Answers

The problem you are having is caused by the way events are propagated up through the DOM tree. When you click an element on the page, that element's click handler will be given a chance to respond to the click. Unless the handler stops the event propagation, the elements parent will be given a chance to handle the event, and so on until the root element is reached.

This behavior normally feels natural and every element "behind" the clicked element will get a chance to respond to the event. However, when you are using absolute positioning, you can place an element in front of another element which isn't its ancestor in the dom tree. At this point the event propagation can be confusing. Only the clicked elements ancestors receive the click event, meaning that the elements behind it may not.

I created a jsfiddle - http://jsfiddle.net/HUGNd/ - to illustrate this situation.

One quick way to fix it would be to make sure the element you want to respond to the click event is an ancestor of the element that gets clicked. Otherwise you can probably achieve the desired results in javascript regardless of which element's event handler is called.

like image 88
tilleryj Avatar answered Nov 04 '22 23:11

tilleryj