Pointer Events explained

— 4 minute read

permalink

In much of my code, you've seen the use of pointer-events: none;, and I've mentioned it is because we only want JavaScript to go off on the main element, but let's explain a bit better.

HTML Structure permalink

So for our demo we are going to make a wrapping div setup

<div class="container center" data-name="container">
<div id="wrapper" class="center" data-name="wrapper">
<div class="inside center" data-name="inside">
<i class="center" data-name="icon">🤟</i>
</div>
</div>
<div id="response" class="center"></div>
</div>

We created multiple divs and gave all a data-name attribute. This will be printed in the response div as output. But as you click around in our demo below, you will see each element will be, where we want the whole element to be treated as one.

JavaScript setup permalink

var response = document.getElementById('response');
document.addEventListener('click', function(event) {
response.innerHTML = event.target.dataset.name;
});

We get our response div and we add a global eventListener to listen for all clicks. We then set the response to show the dataset name of the element we clicked on.

Try out this demo and see the response:

See the Pen Pointer Events explained - started by Chris Bongers (@rebelchris) on CodePen.

Adding pointer-events: none permalink

So to fix this we can add the following CSS.

.container {
> * {
pointer-events: none;
}
}

This tells us every child of the container div should have no pointer-events.

As you can see in the following demo, we will now always get container in our response div!

Now try again:

See the Pen Pointer Events explained - none by Chris Bongers (@rebelchris) on CodePen.

Thank you for reading, and let's connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter