views:

329

answers:

1

Hey,

I've got problems with the jQuery scrollTo plugin. I've got 2 DIVs (nav2 and content) and I'm filling them via ajax calls:

var myJs = { ...
getWithAjax : function( targetFile, targetDivId, anchorId ) {
    // get is jquery function and wraps ajax call
    $.get(targetFile, function(data) {
        $('#'+targetDivId).html( data );
         if(anchorId !== null){
            myJs.doScrollTo(targetDivId, anchorId);
         }
    });

},

go : function(file1, file2) {
    var file1Array, file2Array = new Array();
    if(file1 !== null){
        file1Array = this.splitLinkFromAnchor(file1);
        // update nav2 div
        this.getWithAjax(file1Array[0], "nav2", file1Array[1]);
    },  //... same with file2 but other div "content" 

doScrollTo : function( divId, anchorId ) {
    $( '#' + divId ).scrollTo( '#' + anchorId, 0 );
}
// ... further functions
} // end of object literal

As you see, after getting the content I append it and then try to scroll to a certain position in that target div via an anchorId. This is done via the doScrollTo-function that wraps the jQuery-Plugin-function scrollTo. go is a wrapper for the ajax calls. Before making get-Requests it extracts filename and id (split by '#') from given input parameters. Here's how this all is called:

myJs.go( 'file_a.html#anchor1', 'file_b.html#anchor2' );"

EDIT: With one DIV, the nav2DIV, everything works fine. But the other DIV content is sometimes scrolled, sometimes not. And also, if it is scrolled and a i move the scrollbar of the DIV up and then call go again, it does not scroll anymore. And as I said, this all works fine with the nav2DIV...

Anybody got an idea what I'm doing wrong?

Thanks.

A: 
$.get(targetFile, function(data) {
    $('#'+targetDivId).html( data );
});
if(anchorId !== null){
        this.doScrollTo(targetDivId, anchorId);
}

You're calling doScrollTo before the XMLHttpRequest has completed.

That's the whole point of the callback function you pass into $.get, it doesn't execute straight away, but only when the asynchronous HTTP request is finished. The get method itself returns immediately, so the callback hasn't run and filled in the content by the time you get to the next line with the if.

If you want the scroll to happen just after the content is loaded, you need to put that call inside the callback function you're passing to get. But note that this isn't preserved in callback functions, so you'd have to bind it or use a closure:

var that= this;
$.get(targetFile, function(data) {
    $('#'+targetDivId).html( data );
    if(anchorId !== null){
        that.doScrollTo(targetDivId, anchorId);
    }
});
bobince
thx, that was the solution to the val error.I mean, that's the way asynchronous call work.... :)but another misbehaviour still exists => I edited my question.
zebarto