Nosrettap
Nosrettap

Reputation: 11330

Pass click through to fixed element

I have a static element that is above a fixed element. When the upper static element is clicked, I want to pass this click through to the fixed element. How can I do this? Here is a working example (I wasn't able to get this to work in JSFiddle).

<body>
    <div class="lower" onclick="lowerClick()"></div>
    <div class="upper" onclick="upperClick()"></div>
</body>

<script>
    function lowerClick() {
        alert("LOWER CLICK");
    };
    function upperClick() {
        alert("UPPER CLICK");
    };
</script>


//CSS file
.lower {
    height: 100px;
    width: 100%;
    z-index: -1;
    position: fixed;
    background-color:blue;
}
.upper {
    height: 50px;
    width: 100%;
    z-index: 1;
    position: static;
    background-color:red;
    pointer-events: none;
}

I thought that adding pointer-events:none to my upper element would make this work, but when I click the top element, nothing happens.

Upvotes: 0

Views: 3595

Answers (2)

King King
King King

Reputation: 63347

In fact pointer-events:none works expectedly. But what prevents you from clicking on the lower is the body element. Because of setting z-index:-1 on your lower, it will be sent to behind of its parent (which is the body). So you can set the z-index of the body to a more negative number, of course the postion should be some value other than static (default):

body {
  z-index:-1000;
  position:relative;
}

Demo

Upvotes: 2

scooterlord
scooterlord

Reputation: 15367

You can use the following css for the upper div

.upper {
 pointer-events:none;
}

...also avoid negative z-index, and instead use 1 for lower and 2 for upper. Also why put static and not absolute element at the top?

Upvotes: 1

Related Questions