64

I have a page with some jQuery functions. The HTML on the page looks like so:

<a href="#" class="service">Open</a>

When I click the Open button a hidden panel slides out. The jQuery itself works great however when I click the button it also takes me to the top of the page.

Is this the defualt behavior and how do I prevent every href="#" from taking me to the top of the page.

Note: I could add id's and tell the href to direct to that ID. I do not want to do that for various reasons (including adding unnecessary code).

L84
  • 45,514
  • 58
  • 177
  • 257

4 Answers4

126
<a href="#!" class="service">Open</a>
MyroslavN
  • 1,701
  • 1
  • 12
  • 6
74

In your event handler, add e.preventDefault(); (assuming e is the name of the variable holding the event):

$('.service').click(function(e) {
    e.preventDefault();
});
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • 1
    You may also need to use `return false` at the end of your code block to ignore the browser default of scrolling to the top of the page. – bafromca Jun 26 '14 at 16:56
  • 4
    @bafromca: Absolutely not. Calling `preventDefault` is sufficient; as its name implies, it prevents the default action (following the anchor and going to the top of the page) from occurring. `return false` does this too, and also does the equivalent of calling `stopPropagation` which, as the name suggests, stops the event from propagating up to parent elements; but if all you want to do is prevent the browser from scrolling to the top of the page, there is *no need* for `return false`. – icktoofay Jun 27 '14 at 03:43
  • Another solution for links that don't have a class like the OP - `$('a[href="#"]').click(function(e) {e.preventDefault(); });` – Grant Aug 12 '21 at 07:43
26
<a href="#" onclick="return false;" class="service">Open</a>

OR

$(document).ready(function()
{ 
   var a = $(".service");
   a.click(function()
   {

       return false;

   });
});

OR

$(document).ready(function()
{ 
   var a = $(".service");
   a.click(function(e)
   {

       e.preventDefault();

   });
});

OR

<a href="#" onclick="event.preventDefault();" class="service">Open</a>
Ryan
  • 14,392
  • 8
  • 62
  • 102
0
$('service').click(function() {
<your code>
return false;
});

return false overrides the standard behavior of the ‘a’ tag and stops the browser returning to the top of the page when clicked.

Andreas
  • 2,287
  • 2
  • 23
  • 26