Home > Net >  Check if click event was started inside an element
Check if click event was started inside an element

Time:09-26

Suppose we have stuff like this:

document.querySelector("#foo").addEventListener('click', (e) => {
  console.log(e.target);
});
#foo {
  width: max-content;
  background: #aeaeae;
  padding: 5em;
}

#bar {
  background: #fff;
  padding: 1em;
}
<div id="foo">
  <div id="bar">Text Here</div>
</div>

Now if one tries to select text inside #bar and takes mouse outside it while keeping the mouse button down, the target logged is #foo. Is there some way we can run code inside click handler only if someone has clicked in that gray area?

CodePudding user response:

Listen for mousedown instead of click.

document.querySelector("#foo").addEventListener('mousedown', (e) => {
  console.log(e.target);
});
#foo {
  width: max-content;
  background: #aeaeae;
  padding: 5em;
}

#bar {
  background: #fff;
  padding: 1em;
}
<div id="foo">
  <div id="bar">Text Here</div>
</div>

  • Related