jaka
jaka

Reputation: 155

Is it possible to scroll to anchor after external elements are loaded through jQuery.load()?

The scenario is this:

However, #anchorelement is loaded using jQuery.load() after http://website.com/ is ready. As a result, using the link http://website.com/#anchorelement does not jump to #anchorelement because the element has yet to be loaded when performing the jump.

Does anyone have any suggestions on how to make this work? Is it possible to intercept the anchor jump with javascript and make it wait until the jQuery.load() call is complete?

Thanks!

Upvotes: 2

Views: 1636

Answers (2)

VincentDEJ
VincentDEJ

Reputation: 239

If you have multiple content to load, load it one per one using callback function and if you want to scroll on one of them, call function scroll on the last callback.

$(function ()
{
  //Get the hash and load your content
  var hash = location.hash.replace('#', '');
  loadLocationContent(hash);
});

function loadLocationContent(hash)
{
  $('container1').load("someContent1", function(){
    $('container2').load("someContent2", function(){
      $('container3').load("someContent3", function(){
        $('container4').load("someContent4", scrollToHashAfterContentLoad(hash));
      });
    });  
  });
}

function scrollToHashAfterContentLoad(hash, contentId)
{
  if (hash != '')
  {
    $('html, body').animate({ scrollTop: $('#' + hash).offset().top }, 2000);
  }
}

Upvotes: 0

pawel
pawel

Reputation: 36975

$(function(){
  // so this is inside your document ready function.
  // you need to add a callback
  $( somecontainer ).load('somecontent', function(){
    // after the content has been loaded
    // check if a hash is present in the location
    if( window.location.hash != '' ){ 
      // find an element with matching id
      var anchor = $( location.hash ).get(0);
      // if element was found scroll it into view
      if( anchor ){ anchor.scrollIntoView() }
    }
  });
});

Upvotes: 2

Related Questions