Skip navigation

So, you want to center something in the viewport, and you need the browser window’s dimensions?

If you’re not using a library like prototype, this can be awkward a difficult.

Here’s some code that can help. What it does is get the width and height of the VIEWPORT so you can work with it.

function getWindowDims() {
  return {
  'width' : window.innerWidth ?
            window.innerWidth : //firefox
            ((document.documentElement.clientWidth == 0) ? // are we in quirks mode?
              document.body.clientWidth :  // yes we are, so this is width
              document.documentElement.clientWidth ), // no, so this is width
            
  'height': window.innerHeight ?
            window.innerHeight : //firefox
            ((document.documentElement.clientHeight == 0) ? // are we in quirks mode?
              document.body.clientHeight:  // yes we are, so this is width
              document.documentElement.clientHeight ), // no, so this is width
            
  'scrollTop' : window.pageYOffset ?
                window.pageYOffset : // ff
                (document.body.scrollTop != 0 ? //ie
                  document.body.scrollTop :  // quirks mode ie
                  (document.documentElement.scrollTop) ), // strict mode ie
                
  'scrollLeft': window.pageXOffset ?
                window.pageXOffset :
                (document.body.scrollLeft != 0 ? //ie
                          document.body.scrollLeft : // quirks mode ie
                          document.documentElement.scrollLeft ) // strict mode ie
  
  } ;
}

use:

var dims = getWindowDims(); alert( 'The current width of the viewport is ' + dims['width'] + ' and the height of the viewport is ' + dims['height'] + '\n' + 'The scroll from the top in px is ' + dims['scrollTop'] + ' and the scroll from left is ' + dims['scrollLeft'] );

I use this script all the time in js programs that I need to get the current mouse position in PAGE coordinates. For example, when I’m trying to create a context menu appear at the exact point of the mouse click.

If you just used the event.clientX and event.clientY properties of the event object, then you would get these weird offset coordinates if the page was scrolled to the right or scrolled from the top.

In firefox, the event object does have event.pageX and event.pageY which gets you the correct scroll. But IE has no such property.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: