jQuery Position Tip

I recently switched a project from Prototype/Scriptaculous to jQuery, and overall I’m very pleased with the move. It’s sometimes a little weird using jQuery because I’ve been thinking JavaScript in DOM for so long, but I don’t feel an urge to go back. 🙂

Everything was working great after the conversion, with one exception. Elements that I was absolutely positioning on the page in relation to other elements (get the position of element X and set element Y accordingly) were just a little bit off on the initial page load. Resizing the window would fix it, but it was a problem.

The problem and solution turned out to be rather simple.

The Problem

I was initially using the very cool $(document).ready() feature of jQuery to position and display these elements when the DOM was loaded, but without waiting for all of the images, etc. to load in. However, this doesn’t work very well because until all of the images load in, the browser isn’t sure if it needs to show scrollbars or not. The elements I was positioning were slightly left of their intended position because the elements underneath would shift to the right after the browser determined that no scrollbar was required.

The Solution

Use $(window).load() instead of $(document).ready(). Yes this means you have to wait longer to position your elements, but they go where they are supposed to – which is important. 🙂

The other option is to just nudge them a little by calling the position code again on $(window).load(), but in my situation that was pretty annoying.

Hopefully this will save some other jQuery newbies some debugging time.