DEV Community

Discussion on: Adding Event Listeners to the future DOM elements using Event Bubbling

Collapse
 
sunbeamrapier profile image
SunbeamRapier

Ok, for reactJS users a workable solution is:

var rootElement = document.getElementById('root');
console.log(rootElement);
rootElement.addEventListener('click', rootElementClicked);

console.log('event listener added to root element');

function rootElementClicked(event) {
  event.preventDefault();
  const { name, value } = event.target;

  console.log("Root element clicked with [" + event.target.className, event.target.id);
}
Enter fullscreen mode Exit fullscreen mode

So, the event-listener is app-wide, so a click anywhere will call the event-handler function. Then in the code for that function, the element class and ID will tell you what was clicked.

Rapier...

Note the event.preventDefault(); line - it prevents a refresh of the web page, otherwise the target class & ID are returned as "undefined"

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

Why "root" ? You can attach it to the body in react too.