kojiro
kojiro

Reputation: 77137

Can I get back to normal scroll-to-target behavior with asynchronous content?

I'm loading content on demand on a webpage I'm working on. For various reasons, I'm also using the default browser behavior of scrolling to the :target fragment. You know, you click on a link that looks like #abc and the browser scrolls to id="abc" in your page.

Except that's not exactly what happens when the content is made available asynchronously. According to my test page, you have to click the link twice in order to have the the browser scroll to the asynchronously-added element or the CSS3 :target selector select it. So what I can do about it so that my users don't have to click twice?

Upvotes: 0

Views: 112

Answers (1)

Rob W
Rob W

Reputation: 349142

Add a callback function to .load, which scrolls to the just-added element.

$(document).ready(function () {
   "use strict";
   $("a[href=#loadme]").click(function () {
       if ("testcomplete" in window && window.testcomplete) {
            return;
       }
       $("#loadhere").load("loadme.inc", function(){
            location.href = this.href;
            //Your method to scroll "for various reasons"
       });
       window.testcomplete = true;
       return true; //Prevent default behaviour, ie following the `href` target
   })
})

Upvotes: 1

Related Questions