1

If I define a function like this:

function doSomething()
{
 this.style.color = '#cc0000';
}

Do

element.attachEvent('onclick',doSomething)

and

element.addEventListener('click',doSomething,false)

get the same result? And why?Thanks a lot.

Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Apr 1, 2011 at 7:34
2
  • 1
    No. When using attachEvent in IE, the listener's this keyword is set differently to how it is set by addEventListener in every other browser. In IE, this within the function will be window, in other browsers it will be the element that the listener is attached to. Commented Apr 1, 2011 at 8:04
  • Am I correct that this code is from this page on PPK's QuirksMode site? What, specifically, are you having trouble with in his explanation? Commented Apr 2, 2011 at 11:29

2 Answers 2

4

Yes, but in different browsers.

  • attachEvent is the method you have to use in IE.

  • addEventListener is available in all other browsers (Firefox, Chrome, Safari, Opera, etc). It is the W3C standard. IE9 tries to be more compatible with W3C and supports it too.

I suggest to read Advanced event registration models which explains the browser differences quite well.

You should also read the other articles about events on quirksmode.org. They will give you a good in event handling in general.

answered Apr 1, 2011 at 7:37
Sign up to request clarification or add additional context in comments.

4 Comments

IE9 supports addEventListener nowadays
this will be the global object inside doSomething() using attachEvent() whereas it will be the element using addEventListener, so the OP's code won't work in the first case.
@TimDown: Oh really? I didn't know that (clearly I don't have so much practical IE experience ;)).
Yep, definitely. I'd suggest adding a note to your answer for future readers, because it's misleading at the moment: the OP's code won't work in IE because of the this problem.
1

Pretty much, addEventListener is the W3C way of adding events and supported by most browsers, while attachEvent is an IE thing and supported mainly by them. Read more.

answered Apr 1, 2011 at 7:38

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.