JavaScript Coding Standards - Window Event Chains

view a random?

JavaScript Window Event Overrides
Often developers come across a problem where they require functionality to occur on window resize, load, or close. Sometimes (in larger projects) the developers do not have access to the body tag or the head of the html document. In these situations, the developer may attach a function to the window.onload (or other) property.

However, when this is done, the previous funcitonality is lost. A better solution is to cache the old functionality.

For example:

function setWindowEvents(){
var oldResize = window.onresize;
window.onresize = function(){
if(oldResize) oldResize();
// new functionality here
}
}
setWindowEvents();

This implements a chaining of functionality that can be reused several times in html document, without losing, or disabling hierarchial functionality. The order of the above code is important. It is possible to pass the function that we wish to be run, to the function.

The variable oldResize is not global (nor do we want it to be - this would detriment the repeatability of this code). The variable oldResize is visible in the scope of the outer function.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • Google
  • MisterWong
  • Reddit
  • Scoopit
  • StumbleUpon
  • Technorati
  • rss

Post a Comment

You must be logged in to post a comment.