Thursday, October 2, 2008

jQuery.ScrollTo and Dynamic Content

I have a page which displays dynamic content pulled from the database.  I need to scroll the page to a specific element upon loading, so I look around and found that jQuery.ScrollTo is very helpful. I could write a code as simple as

$.scrollTo($('#div1'), 500)

where 
$('#div1') is the element I want my page to scroll to and 
500 is a length (in millisec) of animation showing a page scrolls from the top to that element.

Nice, right?

I stuck the code in $(document).ready() function. Rendered it in IE8. Looked Great. 
Tried in Firefox3. Ding! It doesn't work. I would expect the result the other way around... ;P

So, I tried another option - passing absolute position instead jquery object to scrollTo method.

$(document).ready(function() {
var pos = $('#div').position();
$.scrollTo(pos, 500);
});

Still, it doesn't work on FF! Worse, it threw exceptions:
[Exception... "Could not convert JavaScript argument arg 0 
[nsIDOMViewCSS.getComputedStyle]" nsresult: "0x80570009 
(NS_ERROR_XPC_BAD_CONVERT_JS)" 
location: "JS frame :: http://localhost:8888/scripts/jquery.js :: 
anonymous :: line 871" data: no]

WTH...

I googled around. These 2 links saved me.
Ok. I'm not crazy. This problem is a known problem. Position() returns a value properly only if the 
element is visible.

Ahhhh, I should try doing this AFTER my element is loaded on the page.

$(window).load(function() { 
$.scrollTo($('#div1'),500); });

This works!

Alright, let's try one more thing. I put the following snipplet in $(document).ready() function.

$('#div1').load(function() { 
$.scrollTo($('#div1'),500); });

It doesn't work.  Oh well,   the documentation explains it.
"When bound to the window element, the event fires when the user agent finishes loading all content within a document, including window, frames, objects and images. For elements, it fires when the target element and all of its content has finished loading. Note: load will work only if you set it before the element has completely loaded, if you set it after that nothing will happen. This doesn't happen in $(document).ready(), which jQuery handles it to work as expected, also when setting it after the DOM has loaded."

I will just stick to what works :)

No comments: