This is a script I've used for a long time using XMLHttpRequest, and I'm converting it to jQuery.
The script takes a defined scrollID (the ID of the element in the loaded PHP file) and scrollto (the ID of the element to which it should automatically scroll, which is a child element of scrollID). Here's where I am so far:
jQuery.fn.ajax = function(whichID, url, scrollID, scrollto) {
// Load the PHP page, not really relevant to this thread other than for reference
var this_url = url.substr(0, url.indexOf('?'));
var query_string = url.substring(url.indexOf('?') + 1);
$(document).ready(function() {
$('#' + whichID).load(
this_url + '?' + $.param({ query_string })
);
});
// Here's where the relevant part about scrolling is
alert($('#' + scrollto).offset().top);
$('#' + scrollID).animate({ scrollTop: $('#' + scrollto).offset().top });
//// This worked when I used XMLHttpRequest, maybe it will help explain my goal
// if (scrollID && scrollto)
// document.getElementById(scrollID).scrollTop = document.getElementById(scrollto).offsetTop;
}
So in the HTML we have:
<div onClick="$().ajax('someID', 'whatever.php?var1=this&var2=that', 'container', 'child');">
<div id="someID"></div>
Then in the loaded PHP, we have:
<div id="container">
blah blah blah
<div id="child"></div>
</div>
The problem with the above is:
1. The first time I click to load the PHP, the PHP loads but I get no alert() and no scroll. The second time I click, though, I get an alert (in my test case, 1144), but no scroll.
2. If I remove the alert, then the first time I click the PHP loads, but there's no scroll. The second time I click, it scrolls upward quickly, as if it started at 1144 and is now quickly scrolling back to 0... kind of the opposite of what I'm trying to do.
For the sake of testing, I changed the line after the alert() to:
$('#' + scrollID).animate({ scrollTop: 1144 });
but it did the same thing (fast scroll to the top on the second load).
Any suggestions?