Search code examples
javascripthtmlprototypejs

Why isn't scrollTo scrolling to my anchor?


i have

<!DOCTYPE html>
<html>
<head>

[...]

<script type="text/javascript" src="jquery-1.7.js"></script>

<script type="text/javascript" src="prototype.js"></script>

<script type="text/javascript">
function getusto(anchorid) {
$(anchorid).scrollTo();
} 

</script>

[...]

</head>
<body>

[...]

<a class="menu_links" href="#" onclick="getusto('welcome');">Welcome</a><br> 
<a class="menu_links" href="#" onclick="getusto('guidelines');">Guidelines</a> 

[...]

<a name="welcome" id="welcome"></a> blah balhb albha 

[...]

<a name="guidelines" id="guidelines"></a> blah blahb alhb

[...]

</body>
</html>

why does clicking the welcome/guidelines links not scroll to the anchors?

i am trying to link to the ids specifically, due to using jquery-bbq which makes it (as far as i can tell) so i CAN'T use hashes/anchors normally.

they are making me use more characters to explain the code. how about we play one frame pac-man:

("< . . . . o . . . . 
                    . 
                    .
                    .
                    .
             [Post Your Answer]

Solution

  • It's possible that the browser is performing the Element.scrollTo function and then following the link... which takes you to the top of the page (since the href is #).

    Why not try one of these two things and see what happens:

    Try return false; from the onclick: (see fiddle here)

    <a class="menu_links" href="#" onclick="getusto('welcome'); return false;">Welcome</a>
    <a class="menu_links" href="#" onclick="getusto('guidelines'); return false;">Guidelines</a> 
    

    Or make getusto return false: (see fiddle here)

    function getusto(anchorid) {
      $(anchorid).scrollTo();
      return false;
    } 
    

    ...and return its value from the onclick:

    <a class="menu_links" href="#" onclick="return getusto('welcome');">Welcome</a>
    <a class="menu_links" href="#" onclick="return getusto('guidelines');">Guidelines</a> 
    

    Doing either of the two suggestions should allow the Element.scrollTo to take effect without following the original destination of the links.