Search code examples
jqueryanchorscrolltopanchor-scroll

jquery hash link to new page scrolling to different anchors


I am using some jQuery to do the following:

From page 1, link to anchor on page 2 - but load the page first, then scroll to the anchor.

<script type="text/javascript">
 jQuery(function(){
    jQuery('html, body').animate({
        scrollTop: jQuery('.Anchor').offset().top
    }, 2000);
    return false;
    });
</script>

My link is like this domain.com/page2.html#anchor-name

The anchors are like this:

<div name="anchor-name" class="Anchor">&nbsp;</div>

The above works fine for just 1 anchor.

Ho do I edit the above jQuery, so that I can have multiple anchors on page 2 & links to them.

i.e.

<div name="anchor-name" class="Anchor">&nbsp;</div>
<div name="anchor-fred" class="Anchor">&nbsp;</div>
<div name="anchor-bert" class="Anchor">&nbsp;</div>

Solution

  • I think this should work?

    Link to it as domain.com/page2.html#fred

    <script type="text/javascript">
     jQuery(function(){
        jQuery('html, body').animate({
            scrollTop: jQuery(window.location.hash + "-anchor").offset().top
        }, 2000);
        return false;
        });
    </script>
    
    <div id="name-anchor">&nbsp;</div>
    <div id="fred-anchor">&nbsp;</div>
    <div id="bert-anchor">&nbsp;</div>