1

I'm developing a website which involves the user being able to navigate to different parts of a page from other pages using # values in the address bar.

I have written a jQuery function to handle the scrolling here:

jQuery.fn.scrollToDiv = function(navheight)
{
    if (!navheight)
    {
        navheight = 30;
    }

    var offset = this.offset();
    var offsetTop = offset.top;
    var totalScroll = offsetTop-navheight-27;
    $('body,html').animate({
            scrollTop: totalScroll
    }, 500);
}

And I am calling the function in 2 different scenarios; when the user clicks a link where the object is on the current page, and when the user clicks a link that takes them to another page before scrolling to the element. See below:

When you are on the page:

$('.gotoPage').on('click', function(e)
{
    e.preventDefault();
    var sPath = window.location.pathname;
    var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
    if (sPath != '' && sPath != 'home')
    {
        var href = $(this).attr('href');

        handleScroll(href);
    }
});

and when you are not on the page:

$(document).ready(function(e) 
{    
    var target = window.location.hash;

    if (target != '')
    {
        $(target).scrollToDiv(30);
    }
});

It works perfectly when you are on the page and click the link, however when you're not on the page, it takes you to the subsequent page as you'd expect but it doesn't then scroll to the required element.

Let me know if you need any more information

Thanks in advance

EDIT: Added function handleScroll(target)

function handleScroll(target)
{
    if (target != '')
    {
        $(target).scrollToDiv(30);
    }
}
Zach Ross-Clyne
  • 779
  • 3
  • 10
  • 35
  • Do you get any errors in the console? Maybe the `target` isn't a valid selector? – Ofir Baruch Jun 23 '15 at 10:11
  • No errors, what I've noticed when refreshing the page is that it scrolls down then jumps back to the top of the page. – Zach Ross-Clyne Jun 23 '15 at 10:13
  • 1
    Maybe it's due to images and styling resources impact of the window's height. `In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.` So put the scroll script (block number 2 in your question): `$( window ).load(function(){...});` – Ofir Baruch Jun 23 '15 at 10:15
  • what does your `handleScroll(href);` function look like? – Pete Jun 23 '15 at 10:17
  • Just added handleScroll to the question, and am I suppose to put the whole `.ready` bit into the `$(window).load()` or just the content of that function? – Zach Ross-Clyne Jun 23 '15 at 10:21
  • Thinking about it, when you click on the link to load your new page, it should load and start at the hash, so animating it to go to the hash won't do anything – Pete Jun 23 '15 at 10:28
  • However when loading the page it starts at the top of the page then should scroll down to the div with the id of the hash – Zach Ross-Clyne Jun 23 '15 at 10:30
  • Then you need to do something to stop the normal browser behaviour of jumping to the hash before you do your animation: http://stackoverflow.com/questions/3659072/how-to-disable-anchor-jump-when-loading-a-page – Pete Jun 23 '15 at 10:36
  • okay, so putting in the `.load()` has worked.. However I now have another issue, clicking the links on the same page don't seem to work anymore. I've had this a few times, fix one, break the other. Any thoughts would be much appreciated – Zach Ross-Clyne Jun 23 '15 at 10:38
  • Nevermind, that was a caching issue. @OfirBaruch if you could post your solution as an answer so I can accept please :) – Zach Ross-Clyne Jun 23 '15 at 10:41
  • If it was a caching issue so my suggestion weren't helpful, therefore - you should add an answer that indicates it was a caching issue or delete the question. Glad it worked for you anyway. – Ofir Baruch Jun 23 '15 at 11:34
  • No I had a caching issue with the second issue, not the first. The first (orignal post) issue you solved! – Zach Ross-Clyne Jun 23 '15 at 14:35
  • @OfirBaruch Your comment was the solution, and I thought that caused another issue, but that second issue was caused by the cache, so your solution did work! Please could you post your answer as to help others in the future should they need it – Zach Ross-Clyne Jun 24 '15 at 07:36
  • 1
    Oh, great. I'll post it indeed. – Ofir Baruch Jun 24 '15 at 08:59

1 Answers1

2

Following your comment:

I've noticed when refreshing the page is that it scrolls down then jumps back to the top of the page

It seems that your script does work, but something affecting it afterwards. I believe that there are some resources as additional css codes or images that aren't being taken in account when the scroll animation takes effect and since that function works by top offset - you must be sure that you're using it after all the resources that might affect the document's height or element's offset, are being loaded.

Therefore, instead of using your script in .ready(), use .load().

.ready() vs. .load()

In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

Community
  • 1
  • 1
Ofir Baruch
  • 10,323
  • 2
  • 26
  • 39