Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between addEventListener and attachEvent? [duplicate]

Tags:

javascript

This is the code i used in my page,

if (window.addEventListener) {    window.addEventListener("load", createIframe, false);             } else if (window.attachEvent) {    window.attachEvent("onload", createIframe);             } else {    window.onload = createIframe;            } 

Please explain me that where my createIframe funtion get called? and what is the difference between addEventListener and attachEvent? and what is the different between load and onload? totally confused to find difference between addEventLisener with load and attachEvent with onload

like image 684
RaJesh RiJo Avatar asked Jun 18 '15 11:06

RaJesh RiJo


People also ask

What is attachEvent?

Browser support: Registers an event handler function (event listener) for the specified event on the current object. The event listener will be called every time when the event occurs on the current element.

How does addEventListener work?

The method addEventListener() works by adding a function, or an object that implements EventListener , to the list of event listeners for the specified event type on the EventTarget on which it's called.

What is an event listener?

An event listener is a procedure or function in a computer program that waits for an event to occur. Examples of an event are the user clicking or moving the mouse, pressing a key on the keyboard, disk I/O, network activity, or an internal timer or interrupt.

What is an event listener in JS?

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.


1 Answers

Quick answer: you have to use attachEvent if your browser returns undefined == window.addEventListener. Thing is the former is a non-standard JS function implemented in IE8 and previous versions, while addEventListener is supported by IE9+ (and all the other browsers).

So the big question is: are you gonna support IE8-?

Margin note: window.onload = whatever will override any attached event listeners. This is why addEventListener is used: to add a function to the event's stack, instead of overwriting it.

like image 107
Jack Avatar answered Oct 13 '22 21:10

Jack