Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener() as a global function

Tags:

javascript

dom

I just caught up in a confusion.
if suppose I implement addEventListener() as a global function (unlike as a method of some specific node like node.addEventListener() ) then does it act just like a usual global function or something goes under the hood while executing the code ending up becoming a method of some specific node

Note: DOM level 2, which defined the addEVentListener, stipulates that handler gets registered to the node. so which node is it registered to; window object is not a node

like image 289
Jake Avatar asked Apr 22 '17 10:04

Jake


People also ask

Is addEventListener global?

Registers an event listener in the global scope, which will be called synchronously whenever the event type is dispatched.

What is purpose of using addEventListener () method in JavaScript?

The addEventListener() method makes it easier to control how the event reacts to bubbling. When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

Is addEventListener the same as on ()?

addEventListener() is a method of a normal DOM element and . on() is a jQuery object method. As you probably know, a jQuery object can represent more than one element and when you use the . on() method you are attaching and event handler to every element in the collection.

How do you call a function in addEventListener?

The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers. Syntax: element.


1 Answers

It will applies to the global object window (which have the function addEventListener). Because:

var a = 5;

console.log(a);
console.log(window.a);

Thus:

addEventListener( ... );

is the exact same things if you use:

window.addEventListener( ... );
like image 108
ibrahim mahrir Avatar answered Oct 13 '22 22:10

ibrahim mahrir