views:

333

answers:

3

How do you I stop my links like this:

<a href="#" onClick="submitComment()">

From jumping to the top of the page after the click?

A: 

You could use this alternative syntax instead:

<a href="javascript:submitComment()">
Dan Diplo
Don't do this. Javascript belongs in the onclick handlers, not the href.
Daniel Roseman
Tell that to the people who wrote StackOverflow! Look at the page source. But you are right, it's not best practice in most cases, but does solve the problem never-the-less.
Dan Diplo
@Dan, I can't see any usage of the javascript: pseudo protocol within an HREF attribute within the SO source...
J-P
+7  A: 
<a href="#" onClick="submitComment(); return false;">

Or with jQuery:

$("a#myLink").bind("click", function(e){
  e.preventDefault(); /* prevents default behavior */
  submitComment();
});
Jonathan Sampson
Correct. However, @ian, JavaScript attributes in html are generally frowned upon.
Justin Johnson
Javascript should be used as an enhancement rather than a prerequisit to functionality. it would make more sense to use an input type=submit button and to use JQuery validate (assuming your using js to pre-validate) and ensuring you have serverside checks to ensure data is validated on being sent. This way you provide the best of both worlds without using anchor tags.Also in XHTML onClick should read onclick as in XML all attributes are lowercase :o)
Chris M
+2  A: 

Add a return false. I believe that without that the page will reload.

<a href="#" onClick="submitComment(); return false;">
Chris Brandsma
no, just scroll to empty anchor, that placed at the top of the page
Sergey Kovalenko