20

Is there a way to register a global onclick listener that will fire anytime an element is clicked? Need to also get the id of that element.

Bogdan Zurac
  • 6,348
  • 11
  • 48
  • 96

3 Answers3

32
document.addEventListener("click", function(evnt){
    console.log(evnt.target.id);
});
emd
  • 1,173
  • 9
  • 21
  • What speaks against "addEventListener"? Which will probably translate to "window.addEventListener"? – codepleb Sep 02 '21 at 14:44
3

You can get id this way using javascript:

window.onclick = function(event) {alert(event.target.id);}
<div id="dID">div</div>
<button id="bId">Button</button>

<input type="text" id="txtId" class="txtclass" />
ketan
  • 19,129
  • 42
  • 60
  • 98
1

Check this code, I haves used it in my live project for tracking users behaviour.

document.addEventListener('click', (event)=> { 
    console.log('emitting click events');
})

document.addEventListener('dblclick',(event)=>{
    console.log('emitting double click events');
} )

document.addEventListener('contextmenu', (event)=>{
    console.log('emitting right click events');
})

document.addEventListener('mouseenter',(event)=> {
   console.log("mouse enter, hovering started")
})

document.addEventListener('mouseleave', (event)=> {
console.log("hovering finished")
})