lukaszkups
lukaszkups

Reputation: 5980

scroll to DOM id after Ajax load new content

I've wanted to dynamically display my portfolio content on the site - reloading whole page(header + content + footer) by ajax and now it works fine, but the site is pretty long and it shows after loading the bottom of it - how automatically scroll to portfolio section after load? I've tried using .scrollTo() but it doesn't work (maybe I'm putting it in the wrong line - please take a look at my code:

$(function(){
  $(".screen.fifth a[rel='tab']").click(function(e){
    //e.preventDefault();
    /*
    if uncomment the above line, html5 nonsupported browers won't change the url but will display the ajax content;
    if commented, html5 nonsupported browers will reload the page to the specified link.
    */

    //get the link location that was clicked
    pageurl = $(this).attr('href');

    //to get the ajax content and display in div with id 'content'
    $.ajax({url:pageurl+'?rel=tab',success: function(data){
      $('.screen.fifth .main_wrapper').html(data);
    }});

    //to change the browser URL to the given link location
    if(pageurl!=window.location){
      window.history.pushState({path:pageurl},'',pageurl);
    }
    //stop refreshing to the page given in
    return false;
  });
});

Please help!

EDIT:

I've changed the link to this page to <a href=".../project_one.php#project_tag"> and in chrome it works just fine, but in Firefox it behaves like I've described earlier :/

Upvotes: 1

Views: 2785

Answers (2)

chrisbradbury
chrisbradbury

Reputation: 327

it looks like what's happening is that the page is jumping to the #projects anchor and then the page resizes when it's loaded.

So, if you put the following:

goToByScroll( window.location.hash.substring(1) );

after the code where the page resizes ($('.map').width(myWidth);) in both the ready and resize functions, that should solve your problem

Upvotes: 1

chrisbradbury
chrisbradbury

Reputation: 327

Use this function:

function goToByScroll(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top - 30},'slow');
}

It scrolls to an inputted id, so, if you want to scroll to #portfolio_tag then call:

goToByScroll('portfolio_tag');

once the AJAX call has been completed.

Upvotes: 1

Related Questions