Skip to content

Triggering a ‘click’ event on the element ONLY without taking its padding into account

The goal is to trigger a ‘click’ event on the element ONLY when the user clicks directly on the element excluding its padding. Thus, suppose we have something like:

  <li>First element</li>
  <li>Second element</li>

Let’s say those list elements are aligned on the same row. So, there might be a case when the user clicks on the ‘space’ that is somewhere in the middle of those two elements, or even closer to the second one. It’d be more intuitive if no event was triggered in this situation rather than any of those two.


in your HTML wrap <li> contents in a <span>:

  <li><span>First element</span></li>
  <li><span>Second element</span></li>

in your CSS set the padding for <li>. for example:

li {
  padding: 20px;

And in your JS set click event for <span> (NOT <li>):

let firstElement = document.querySelector('li span');
firstElement.addEventListener('click', clickHandler);