4

I have the following Javascript code.

When the page is loaded it is scrolled to the right position. When I click on the link to run the function the page scrolls to the top of the page.

How do I fix this?

<html>
    <head>
        <script  type="text/javascript">
            function scroll() {
                window.scrollTo(0, 400)
            }
        </script>
        <title></title>
    </head>
    <body onload="window.scrollTo(0, 400)">
        <img src="a.jpg"/>
        <a href="#" onclick="scroll">comments1</a>
    </body>
</html>
Jon Adams
  • 24,464
  • 18
  • 82
  • 120
johnk
  • 390
  • 1
  • 4
  • 14

2 Answers2

6

Use

onclick="scroll(); return false;"

that should fix it.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
1

To add a bit more detail, with the return false;, the click event continues after the page is scrolled, and the click event follows the href to #, which is the top of the page. An alternative way to fix this is:

<a href="javascript:void(0);" onclick="scroll">comments1</a>

Returning false is better, IMO, but this would also do the trick.

Bialecki
  • 30,061
  • 36
  • 87
  • 109
  • 1
    You must still *call* the function ("`scroll();`"), not just reference it (`"scroll"`). – npup Mar 27 '10 at 21:54