AutoLogin

A CakePHP Component that will automatically login the Auth session for a duration if the user requested to (saves data to cookies).

Getting the page height with jQuery

Tuesday, December 14th 2010, 11:41pm
Topics: jQuery
Tags: jQuery, Height, Window, Document, Modal, Overlay
Comments: 2
Permalink - Tinylink

I was recently adding an overlay (or modal) feature to one of my sites. This overlay feature required a blackout mask (when your webpage gets covered with an opaque black layer) to be shown over the content. Writing the CSS for this was a breeze, and writing the jQuery (or Javascript) for this was even easier. However, I did run into one little snag.

In current browsers I could do a position fixed on the blackout and define width and height at 100%. While in outdated browsers (Internet Explorer), position fixed does not work properly, so I had to resort to Javascript and position absolute. This was easy as I would grab the height of the page and apply it to the blackout CSS. During my testing I noticed that the blackout would only fill the viewport of the page, and the second you started scrolling you would see where the blackout cut off.

After some browsing of the jQuery API I discovered my problem. It seems that the window and document objects return different heights in jQuery. Window returns the height of the viewport (everything within view) while document returns the height of the HTML page (the whole page, including hidden content that requires scrolling). Furthermore, window and document can not use outerHeight() nor innerHeight(), they must simply use height().

$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document


Here is how I remember which is which: document returns the height of the DOM (document object model) and window returns the height of the viewport (viewing out a window). I know many of you may of already known this, but it slipped past me and was quite a genius implementation of behalf of the jQuery team.
Related Entries:

2 Comments

10 / 2 = ?
Allowed: [code] [b] [i] [u]
  • James
    jblotus.com
    Dec 15th 2010, 10:33
    1 Good all around tip, seems that creating a modal window without a plugin should now be a part of every developers toolbox.
  • Ryan Barr
    spookyismy.name
    Apr 30th 2011, 13:12
    2 I ran into this same problem working on a project where I was confined to an IFrame. Since the domains didn't match, I would get security exceptions when attempting to get the height of the window object.