What's the distance between elegant and ugly?

4 pixels, apparently.

I have some JavaScript code that uses jQuery to get the height of a web page to determine whether we should do some auto-scrolling as we add new content to the page. I do this by comparing the height of the document and the window like this:

var $win = $(window);
var currentPos = $win.height() + $win.scrollTop();

if (currentPos == $(document).height()) {
    // The user is at the bottom of the page.
    shouldScroll = true;
} else {
    shouldScroll = false;
}

Unfortunately, Internet Explorer 8 acts weird when it comes to comparing the height of window and document. When there's no scroll bar on the page, the height of the document is always 4 pixels more than the height of the window. You can see this happening even on the jQuery documentation for height. Chrome, Firefox and IE9 will report 125px for both document and window height. IE8 will report the window height as 121px.

So, $win.height() + $win.scrollTop() is always 4 pixels less than $(document).height() which causes my scrolling feature to kick in, even when there's no scrolling to do. As a result, I had to turn that elegant piece of code into this monstrosity just because of IE 8:

// This first check is an ugly hack to deal with the fact that
// IE 8 reports document height to be window height + 4 pixels
// in the absence of a scroll bar.
if ($win.scrollTop() == 0) {
    if (currentPos + 4 >= $(document).height()) {
        // User is at the bottom of the page
        scrollResult = true;
    } else {
        scrollResult = false;
    }
} else {
    // Just the following code would be sufficient if it weren't
    // for IE 8.
    if (currentPos == $(document).height()) {
        // The user is at the bottom of the page.
        scrollResult = true;
    } else {
        scrollResult = false;
    }
}

No Comments