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?
If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded.
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.
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.
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.
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.
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() {}
Just put the function initialiseTable to the first position, eg:
var initialiseTable = function (){ /*[...]*/ }
After continue calling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With