Extend an event in javascript
By Anatoly Mironov
If you use jQuery, you don’t need it. But if you for some reason must use javascript you must beware of adding events. The most dangerous is window.onload. Consider this scenario:
function doSomethingGreat() {};
window.onload = doSomethingGreat;
```It works fine if you are the only person who writes window.onload handler. But on such platforms like SharePoint you can't know which events exist. And if you just write **window.onload = doSomethingGreat;** you override all other window.onload events. Again, in jQuery you have nothing to worry. jQuery(window).load(doSomethingGreat) will just add your event, not override. In this post I'll show how to extend an event handler the pure javascript way. We have to create our own function for adding event handlers. First the old events have to be temporary saved and then the new event has to be added. [Like this](http://jsfiddle.net/mirontoli/cnN6s/):
function addOnclick(elem, func) {
var old = elem.onclick;
if (typeof elem.onclick != ‘function’) {
elem.onclick = func;
} else {
elem.onclick = function () {
if (old) {
old();
}
func();
};
}
}
func1 = function() { window.console.log(“lapin”); } func2 = function() { window.console.log(“kulta”); }
var elem = document.getElementById(“mydiv”); addOnclick(elem, func1); addOnclick(elem, func2);
Unfortunately **+=** operator doesn't work. If you do so, the onclick event just get a string of two functions, and the click event doesn't do anything: [![](https://sharepointkunskap.files.wordpress.com/2011/11/plus-operator.png "plus-operator")](https://sharepointkunskap.files.wordpress.com/2011/11/plus-operator.png)