xdevel2000
xdevel2000

Reputation: 21374

Internet Explorer and JavaScript event currentTarget

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 also we can use the this keyword to refer to the object processing the event.

But in Internet Explorer we don't have currentTarget property and the this refers to window object!

So how can I do that?

Upvotes: 44

Views: 54977

Answers (13)

HQCasanova
HQCasanova

Reputation: 1158

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);

Upvotes: 0

Ignas2526
Ignas2526

Reputation: 542

This function creates currentTarget in case it is IE, so you no longer need to patch your code!

function eventListener(e,t,f) {
   if(e.addEventListener)
       e.addEventListener(t,f);
   else
       e.attachEvent('on' + t,
                     function(a){
                         a.currentTarget = e;
                         f(a);
                     });
}

Regular JS(will not work on IE below 9):

function myfunction(e) {
    alert(e.currentTarget.id);
}

e = document.getElementById('id');
e.AddEventListener(e,'mouseover',myfunction);

With this function(will work on IE below 9):

function myfunction(e) {
    alert(e.currentTarget.id);
}
e = document.getElementById('id');
eventListener(e,'mouseover',myfunction);

Upvotes: 1

rmoestl
rmoestl

Reputation: 3155

Internet Explorer 6 - 8 do not implement event.currentTarget.

Quote from Mozilla Developer Network:

On Internet Explorer 6 through 8, the event model is different. Event listeners are attached with the non-standard element.attachEvent method. In this model, there is no equivalent to event.currentTarget and this is the global object. One solution to emulate the event.currentTarget feature is to wrap your handler in a function calling the handler using Function.prototype.call with the element as a first argument. This way, this will be the expected value.

If you use jQuery anyway, then jQuery takes care of normalizing the event object and its properties (as stated numerous times in the other answers). Quote from jQuery API docs:

jQuery’s event system normalizes the event object according to W3C standards.

Upvotes: 1

Malek
Malek

Reputation: 21

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..

Upvotes: 0

Linus Swälas
Linus Swälas

Reputation: 130

I'd like to give a more simple answer, the meat of this is the same as the meat in anas' and user1515360's answers:

if (browserDoesNotUnderstandCurrentTarget) {
        someElement.onclick = function (e) {
                if (!e) { var e = window.event; }
                e.currentTarget = someElement;
                yourCallback(e);
        }
}
else {
        someElement.onclick = yourCallback;
}

Substitute onclick for whatever event you wish of course.

This makes e.currentTarget available on browsers that do not support currentTarget.

Upvotes: 0

EpokK
EpokK

Reputation: 38092

With Prototype JS you can use :

var target = Event.element(event);

Upvotes: 1

marta.joed
marta.joed

Reputation: 366

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.

Upvotes: 1

gpasse
gpasse

Reputation: 4489

I had similar problem. I solved it using keyword this as stated in an article on brainjar.com

To get the equivalent of the currentTarget property in IE, use the this keyword as an argument when setting the event handler in a tag.

...

function myHandler(event, link) { ... }

On the same page you can find the following table :

enter image description here

Upvotes: 25

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79582

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.

Upvotes: 13

Anas
Anas

Reputation: 21

with this function you can pass the object when adding and get it in the listener. the problem about this is that you have an anonymous function as eventlistener and in actionscript you cannot remove an anonymous listener. dunno bout js.

addEvent:function(object,type,listener,param)
    {
    if(object.addEventListener)
      object.addEventListener(type, function(e){ listener(object, e, param);}, false );
    else
    if(object.attachEvent)
      object.attachEvent('on'+type, function(e){ e = getEvent(e); listener(object, e, param);});
    },

getEvent:function(e)
        {
    if(!e) e = window.event; // || event
    if(e.srcElement) e.target = e.srcElement;
    return e;
    },

removeEvent:function(object,type,listener)
    {
    if(object.removeEventListener)
    object.removeEventListener(type, listener, false);
    else
    object.detachEvent('on'+type, listener);
    }

var div = document.getElementById('noobsafediv');
var div2 = document.getElementById('noobsafediv2');
addEvent(div,'mouseover',mouseover,['astring',111,div2]);


function mouseover(object,e,param)
 {
 console.log(object,e,param);
 }

its my framework and i call it jNoob.

Upvotes: 2

alvincrespo
alvincrespo

Reputation: 9334

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.

Upvotes: 32

Tom
Tom

Reputation: 786

I'm assuming that you're wanting to use the 'this' context because the same handler will be dealing with multliple posible objects. In that case, see the excellent AddEvent script from the quirksmode recoding contest. (http://www.quirksmode.org/blog/archives/2005/09/addevent_recodi.html). This code has allowed me to get the very last of my javascript out of html. More importantly, it seems to work on all of the browsers that I've tested. Simple and compact.

Upvotes: 1

Related Questions