Is there a way to take the current target of an event with IE 7 or 8?
With other browser (firefox, opera, chrome etc.) we can use
event.currentTarget
or
You could always use a closure and pass in the element the event handler has been attached to. Something along these lines...
function handlerOnClick (currentTarget) {
return function () {
console.log(currentTarget);
}
}
var domElement = document.createElement('DIV');
domElement.innerHTML = 'Click me!';
domElement.onclick = handlerOnClick(domElement);
document.body.appendChild(domElement);
Additional note: Sometimes IE (like ie 7) will return undefined for event.target, so it won't even evaluate it as true or false (whether in an if or in a ternary operator). Furthermore, even if you try typeof event.target == 'undefined'
it will still error saying "event.target is undefined." Which of course is stupid because that's what you're testing.
Apparently it is a problem with passing events into functions in older IE. What you do to fix it is:
event = event ? event : window.event;
if (typeof event.target == 'undefined') {
var target = event.srcElement;
} else {
var target = event.target;
}
Make note that you re-write the event in standards compliant browsers and grab the global event for IE.
currentTarget property is supported from IE version 9 onwards.
Try this sample in IE9+
The short answer is: use jQuery.
Although event.currentTarget
is not accessible on IE, jQuery will normalize the event for you so your code would also work on IE (as stated here)
Note that using event.srcElement
, as suggested in other answers is not equivalent, since srcElement
corresponds to the target
, not to currentTarget
, as explained at the end of this page.
well i m not sure but this may be a solution: since the child element given by srcElement is not supposed to have an event because this gonna make interference with the event on the parent element neither any other upper element before the top element where the event statement (like onmosedown="") so this is the code:
if (!event) event = window.event;
if (event.currentTarget) element = event.currentTarget;
else{element = event.srcElement; while(element.onmousedown==null) element = element.parentNode;}
if(element.nodeType==3) element=element.parentNode; // defeat Safari bug
this seems to work fine till now with me please correct me if u find a problem cz i need a solution for that i dont want to use jquery..
You can do something like
target = (event.currentTarget) ? event.currentTarget : event.srcElement;
Although as @Marc mentioned you can use a JQuery framework that normalizes the event for you.