Subscribe

Pointer Events explained

✍️

Explore how pointer-events can help your JavaScript

9 May, 2020 · 2 min read

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

HTML Structure

So for our demo, we will 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 where we want the whole element to be treated as one.

JavaScript setup

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

We get our response div and add a global eventListener to listen for all clicks. We then set the answer 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;
  }
}

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

As you can see in the following demo, we will 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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Show and hide a header based on scroll direction

9 Jan, 2022 · 5 min read

Show and hide a header based on scroll direction

How I made a no-div playground in Vanilla JavaScript

28 Dec, 2020 · 9 min read

How I made a no-div playground in Vanilla JavaScript

Join 2097 devs and subscribe to my newsletter