Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why window.addEventListener does not work? [duplicate]

Tags:

javascript

On the window.onload event, I would like a function to be called. If I define it as given below, the function does not get called.

try {
    window.addEventListener("load", initialiseTable, false);
} catch(e) {
    window.onload = initialiseTable;
}

var initialiseTable = function () {
    console.log("hello world!!");
};

but if I change the function declaration to

function initialiseTable() {
    console.log("hello world!!");};

it works, any idea?

like image 974
101V Avatar asked Jun 20 '13 15:06

101V


People also ask

What happens if you add an event listener twice?

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded.

How do you fix addEventListener is not a function?

To solve the "addEventListener is not a function" error, make sure to call the addEventListener() method on a valid DOM element, or the document or window objects, and place the JS script tag at the bottom of the body tag in your HTML.

Does addEventListener overwrite?

addEventListener does not overwrite existing event listeners, it simply adds a new one as the method name implies. Existing listeners must be removed using the removeEventListener method.

What does Window addEventListener do?

The addEventListener() method allows you to add event listeners on any HTML DOM object such as HTML elements, the HTML document, the window object, or other objects that support events, like the xmlHttpRequest object.


3 Answers

While you using var x = function(){} to declare functions, it should be declare before you call the function.

By function x (){}, x will exist in current scope, no matter how later it declare. Because such side effect, the var x = function(){} are more recommended. For example:

var user = 'alien';
if( user == 'alien') {
    function salute () { console.log("Welcome to Earth!"); }
} else {
    function salute (){ console.log("Good day!"); }
}

The salute() will print Good day! anyway, even though it not we want at all.

like image 155
taiansu Avatar answered Sep 23 '22 23:09

taiansu


Declare the function before.

var initialiseTable = function () {
    console.log("hello world!!");
};
try {
    window.addEventListener("load", initialiseTable, false);
} catch(e) {
    window.onload = initialiseTable;
}

For more information about declaring a function read this: var functionName = function() {} vs function functionName() {}

like image 30
Edorka Avatar answered Sep 23 '22 23:09

Edorka


Just put the function initialiseTable to the first position, eg:

var initialiseTable = function (){ /*[...]*/ }

After continue calling.

like image 39
Mystic Avatar answered Sep 23 '22 23:09

Mystic