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.
The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked. However, they are not the same.
The onclick event in JavaScript lets you as a programmer execute a function when an element is clicked.
An event listener is a procedure in JavaScript that waits for an event to occur. The simple example of an event is a user clicking the mouse or pressing a key on the keyboard.
Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.
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" />
document.addEventListener("click", function(evnt){
console.log(evnt.target.id);
});
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")
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With