Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript global onclick listener

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.

like image 423
Bogdan Zurac Avatar asked Apr 10 '15 06:04

Bogdan Zurac


People also ask

Is onClick an event listener?

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.

What is onClick event handler in JavaScript?

The onclick event in JavaScript lets you as a programmer execute a function when an element is clicked.

What is Eventlistener in JavaScript?

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.

How do you know if an element has an event listener?

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.


3 Answers

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" />
like image 20
ketan Avatar answered Oct 20 '22 20:10

ketan


document.addEventListener("click", function(evnt){
    console.log(evnt.target.id);
});
like image 60
emd Avatar answered Oct 20 '22 19:10

emd


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")
})
like image 1
Sanjaya Bir Bikram Shrestha Avatar answered Oct 20 '22 21:10

Sanjaya Bir Bikram Shrestha