Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add more functions to window.onunload?

Tags:

javascript

suppose I have some javascript which says:

window.onunload=some_jsfunction();

how can I add another function to this handler? something like this:

window.onunload=some_jsfunction() + another_jsfunction();
like image 369
user603007 Avatar asked Jan 23 '26 07:01

user603007


2 Answers

The first and foremost way: addEventListener:

window.addEventListener('unload', function () { /* Do things. */ });
window.addEventListener('unload', function () { /* Do other things. */ });

Another way is too create a new event handler with a call to the old handler from it, then overwrite the old handler. I can imagine a situation where it could be useful, but not with DOM events:

var onUnload = function () {
    /* Do things. */
};

var oldOnUnload = onUnload;

onUnload = function () {
    oldOnUnload();
    /* Do new things. */
};

The most advanced way is creating your own observer on top of the DOM's observer (this is what frameworks like Mootools do internally). It can be helpful in the long term; for example, to add event namespaces.

var handlers = [];

window.onunload = function () {
    handlers.forEach(function (fn) { fn(); });
};

handlers.push(function () { /* Do things. */ });
handlers.push(function () { /* Do other things. */ });
like image 127
katspaugh Avatar answered Jan 24 '26 21:01

katspaugh


Call a function on window.onunload and call your function in that function. Some thing like this

window.onunload = callFunctions;

While your callFunctions look like

function callFunctions() {
  someFunction();
  anotherFunction();
}
like image 33
Awais Qarni Avatar answered Jan 24 '26 21:01

Awais Qarni