Lewis Malpas
Lewis Malpas

Reputation: 111

jQuery: Anchor loads page and then scrolls to div

I have a one page website which scrolls to the correct section when a navigation link it clicked - Please see http://www.cleanupbritain.org for a live example.

I am now extending the website and adding a blog which is located in a subdirectory, I am trying to setup the blogs navigation to load www.cleanupbritain.org and then scroll to the correct section. Is this possible? I am fairly new to jQuery so any help would be great appreciated.

Here is the navigation link:

<a href="http://www.cleanupbritain.org" onClick="goToByScroll('news')">News</a>

And here is the script I have written:

<!-- ScrollTo for navigation scrolling -->
<script type="text/javascript">
jQuery(window).load(function() {
    function goToByScroll(id){
            jQuery('html,body').animate({scrollTop: $("#"+id).offset().top - 236},'slow');
    }
    function goToTop(){
            jQuery('html,body').animate({scrollTop: 0},'slow');
        }
});
</script>

I presume the navigation link is not right, but I am not sure what needs to be changed to ensure the script is executed at the right time?

Many thanks in advance for your help,

Lewis.

Upvotes: 1

Views: 9143

Answers (1)

Andrew
Andrew

Reputation: 1203

The navigation link should say <a href="http://www.cleanupbritain.org/#news">News</a>

Now if the news block has an id="news", the browser will scroll to it automatically -- that's what anchors are made for. If you'd like an animation, then:

<script type="text/javascript">
jQuery(window).load(function() {
    function goToByScroll(id){
       jQuery('html,body').animate({scrollTop: $("#"+id).offset().top - 236},'slow');
    }

    if(window.location.hash != '') {
        goToByScroll(window.location.hash.substr(1));        
});
</script>

Maybe you'll have to change the news' block id to prevent automatic anchor behavior, but you should test.

Upvotes: 6

Related Questions