Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the javascript event object inside a event handler?

I have a div with onclick param:

<div onclick="some_function()"></div>

How can I access the event object inside the function? I need it to get event.target

function some_function() 
{
event = event || window.event;
var target = event.target || event.srcElement;
//does not work in IE and Firefox, but works in chrome
}
like image 953
xCrZx Avatar asked Sep 15 '25 05:09

xCrZx


2 Answers

This way:

<div onclick="some_function(event)"></div>

function some_function(evt) 
{
    // do something with evt (the event passed in the function call)
}

Note that the argument name MUST be event in the function call. In the event handler you can use the name you want.

A live example: http://jsfiddle.net/davidbuzatto/KHyAb/

like image 123
davidbuzatto Avatar answered Sep 16 '25 18:09

davidbuzatto


If we work with event listeners, then you have in 'this' the html element and in 'event' the event object.

<a id="mya" href="#">Link</a>
var myA= document.querySelector("#mya");
myA.addEventListener("click", some_function);
function some_funtion() {
  //Here the html element is: this
  //Here the event object is: event
  //event.target is not always equal to this
}
<div id="mydiv">click here <span>then here</span></div>
var myDiv = document.querySelector("#mydiv");
myDiv.addEventListener("click", other_function);
function other_function() {
    alert(this === event.target);
}    
like image 26
alexyshr Avatar answered Sep 16 '25 18:09

alexyshr