2

I have a hyper link as such <a href="#" id="someID">Link</a> that i have to scroll down the page to get to. This hyperlink is only there to trigger an Ajax request. When ever i click this hyperlink the page scrolls all the way to the top! How can i fix this? I use # because anything else would reload the page. Am I using it wrong?

EDIT:

Its kind of hard for me to explain what am doing so if you run this you get the same problem that i am facing. Even after returning false.

   <html>
    <head>
    </head>
    <body>
        <a href="#" id="link" style="position:absolute; top:200%;">Link</a>
    </body>
</html>
<script type="text/javascript">
    document.getElementById("link").onmousedown = function(){
        this.style.color="red";
        return false;
    }
</script>
Babiker
  • 18,300
  • 28
  • 78
  • 125

5 Answers5

7

add a return false; to the event handler assigned:

 el.onclick = function() {
   // do your code
   return false;
 }

Or the arguably more elegant way

function(e) {
   e = e || window.event;
   if ( e.preventDefault ) e.preventDefault()
   else e.returnValue = false;
}
meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
6

Have to tried javascript:void(0) in place of #?

Source:

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Edit:

Reason:

It prevents the browser from refreshing or navigating to another page.

http://www.tizag.com/javascriptT/javascriptvoid.php

Community
  • 1
  • 1
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
4

The browser is trying to move to an anchor named #. There isn't any so it scrolls to the very top. To avoid this behavior do what meder mentioned.

cherouvim
  • 31,725
  • 15
  • 104
  • 153
1

you need to stop the event propagation when you click the anchor tag.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
0

The browser is reading the # as an anchor, you ether have a link with an id of "someID" at the top of your page or no ID at all in which case it will just go to the top of the page by default (This seems to be the case for you). You will have to replace the # sign with something to stop this. I'm not sure what would be best, but Evan Mulawski's answer might work. I don't know if this will still allow your ajax code to run properly though.

Blake
  • 756
  • 3
  • 16
  • 34