DEV Community

Cover image for Pointer Events explained
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Pointer Events explained

In many 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

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>
Enter fullscreen mode Exit fullscreen mode

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 hit, where we want the whole element to be treated as one.

JavaScript setup

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

We get our response div and we add a global eventListener to listen to 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

So to fix this we can add the following CSS.

.container {
  > * {
    pointer-events: none;
  }
}
Enter fullscreen mode Exit fullscreen mode

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!

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

Top comments (0)