Thursday, September 22, 2011

Detect Horizontal Window Scrolling With jQuery

Chris Domino, Director, Enterprise Architect

This one will be short and sweet. I'm working with a full screen Silverlight application that has a soft minimally-supported resolution. By "soft" I mean that the app will attempt to grow and shrink to fit itself in the screen; for resolutions that are too small, we refuse to shrink and further, and instead force the browser to have to scroll to see our love handles.

I was Binging (which is totally in the Microsoft Word dictionary! Awesome!) around for a way to use jQuery to "detect" if the browser's chrome has horizontal scrolling going on. After much search pagination, I couldn't find anything. So I flipped on IE's Developer Tools, and used the Script Console to execute a bunch of jQuery statements until I was able to reliably get what I was looking for.

Basically, if the document is wider than the window, it's a good bet horizontal scroll bars are visible. For my purposes, I have a popup div that I need to position in the center of the screen. The problem was that the presence of horizontal scrolling screwed up my calculations. (The div was correctly anchored in the middle of the window, but since the Silverlight control behind it scrolled along with the document, it only appeared centered if the horizontal scroll bar was advanced precisely half way.)

Here's the code that fixed this for me. Feel free to grab the pieces that you need:

  1. //get window and document widths
  2. var winWidth = $(window).width();
  3. var docWidth = $(document).width();
  4. //adjust for too small resolutions
  5. if (docWidth > winWidth)
  6. {
  7. //scroll horizontally to middle of screen (where div will be correct)
  8. $(body).scrollLeft((docWidth - winWidth) / 2);
  9. }

This works in IE 9 and FF 6 on PC. Chrome, for some reason, always reported that the document and window (and body) have the same width for my page. I didn't test this on my Mac, because we're currently not on speaking terms.