Skip to content
Advertisement

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:

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

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.

Advertisement

Answer

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

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

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);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement