javascriptscrolltosmooth-scrollingexternal-linksinternal-link

How to transform "javascript:scrollto('.class');" to an external link (leading to a certain .class on the site from the outside)?


I was trying to create a 'one-page-layout' with a smooth scrolling using internal links. This is the code:

function scrollto(element) {
$('html, body').animate({
    scrollTop: ($(element).offset().top - 40)
}, 'slow'); };

There is a fixed header on the page, therefore the value -40.

The script works perfectly within the site, on which it's implemented. For links I use:

<a href="javascript:scrollto('.link1');">Go to Link 1</a>

...and 'tag' the divs with classes:

<div class="link1">
         <h1>This is link no 1</h1> <p>Text</p>
</div>

Here's an example: EXAMPLE SMOOTH SCROLLING

How can I create a link placed on the other website, that would lead to a specified DIV in the my document? Usually, using the anchors, it would be:

<a href="example.html#link1">Go to Link 1</a>

but I do not use anchors and don't really have any good experience with them, because of the fixed header.

Is there any way to transform this internal link

"javascript:scrollto('.link2');"

so that I could link some DIVS from the 'outside'?

Your help is much appreciated. I've been googling much. Can't find the answer though. I am not an advanced javascript user, so please, be understanding. Thank you.


Solution

  • UPDATE

    It's very important to make jQuery work after the page is fully loaded:

    $(window).bind("load", function() {
    //code here...
    });
    

    So that in the end the script should look like this:

    $(window).bind("load", function() {
       window.scrollTo = function (selector) {
            if (selector === '') { return; }
            return $('html, body').animate({
                scrollTop: $('.' + selector).offset().top - 117
            }, 'fast');
        };
        $(document).ready(function () {
            scrollTo(window.location.hash.replace(/^\#/, ''));
        }); 
    });
    

    It solved my problems.