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.
Asked
Active
Viewed 2.9k times
20
-
`` – devqon Apr 10 '15 at 06:46
-
Can't modify the html. – Bogdan Zurac Apr 10 '15 at 06:47
-
Does this answer your question? [How do I handle a click anywhere in the page, even when a certain element stops the propagation?](https://stackoverflow.com/questions/8054429/how-do-i-handle-a-click-anywhere-in-the-page-even-when-a-certain-element-stops) – leonheess Mar 06 '21 at 00:33
3 Answers
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")
})

Sanjaya Bir Bikram Shrestha
- 137
- 1
- 3