DEV Community

Discussion on: Front-end Challenge: Prevent Clicks

Collapse
 
silvestricodes profile image
Jonathan Silvestri

For adding all the events:

const addBlocker = (event) => {
  event.preventDefault()
  event.stopPropagation()
  console.log({
    clientX: event.clientX,
    clientY: event.clientY,
    element: event.currentTarget
  })
}

const allElements = document.getElementsByTagName("*");
for (let i = 0; i < allElements.length; i++) {
  allElements[i].addEventListener('click', (event) => addBlocker(event))
}

And for removing the added event:

// Below: Passing in true for the third parameter causes the event to be captured on the way down. Stopping propagation means that the event never reaches the listeners that are listening for it.

const removeBlocker = () => {
  window.addEventListener('click', (event) => {
    event.stopPropagation()
  }, true)
}

// Sometime later...
removeBlocker()
Collapse
 
entrptaher profile image
Md Abu Taher

Thanks for answering. Did you test this on producthunt?

Apparently there are sites (ie: producthunt) where this should not work because not every click event is a click event. Sometimes there are mousedown and other events such as virtual dom based events as well.

Collapse
 
silvestricodes profile image
Jonathan Silvestri

Nah, just did a rudimentary test in my console.

Sounds like there would need to be bindings for each event, with associated un-bindings for each event as well. Probably doesn't change my solution too much, just needs to be applied to more things.