Wednesday, April 25, 2012

Simple JS Snippet for Adding a .position Function to the window Object

Not a whole lot to explain here.  I'll include a jsFiddle below that will even show you how to put this func on a timer to update value at a certain area (in my case, a pair of table columns) regularly so you can use this func to tell if the window is being moved!

This function is pretty straight forward and simple.  It first checks to see if anything else in the place of `window.position` and if not, it adds the simple function.  The function itself does nothing more than check browser version, then return an object containing an "x" and a "y" reflecting the current browser window's x and y position on your screen.

I forgot to mention, when I first posted this, using this function this way (preferably at the TOP of your JavaScript) not only enables `window.position`, but it actually assigns the function as a "global".  What this means is that you can recall it in most browsers by simply typing `position()`.  Now, just so you know, this is generally advised against for various reason's.  If you don't feel comfortable assigning this as a global function, you can always use a name-spacing ftw.  For more on name-spacing, check out this nice blog here.

The function:

The Example:

No comments:

Post a Comment