The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Scroll offset from one page to another

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #160867

    I am stuck in a bit of a peril. I have a scroll-to-anchor set up on “Page1” of a one-page website with easing.js using JavaScript. Below is my code:

    $(‘a[href^=”#”]’).on(‘click’,function (e) {

    var target = this.hash,
    $target = $(target);

    $(‘html, body’).stop().animate({
    ‘scrollTop’: $target.offset().top – 120
    }, 900, ‘swing’, function () {

    The links are so: <a href="#bodyContainer1">HOME</a> and the body container it is linked to is so:

    <div id="bodyContainer4">
    <img src="images/page4.jpg" width="1024" height="892">

    Now my issue is when i click a link that takes me to another page “Page2”, I have used this syntax to do it: <a href="page2.html#2009">PAGE 2</a> And it goes to that specific section correctly, but it does not scroll up -120px using the offset function ‘scrollTop’: $target.offset().top – 120 in my JavaScript. I have used the above same JS code on “Page2.html” also.

    Could anyone shed some light into this ? I am Fairly new and learning JS.

    Cheers, G



    This happens because the javascript animation is only firing on “Click” of the link, when you click a link that takes you to another page, the new page loads and the event handlers will be re-attached but the click event is never fired so the browser does it’s native thing of just jumping to the anchor position instead of animating,

    To solve this you would have to stop the browsers native action of jumping to the anchor, then check if the current url has an anchor specified, then if it does, animate to the anchor,

    Hope this helps a little

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.