href="#" Going to Top of Page - Prevent?

AnchorHrefHashtag

Anchor Problem Overview


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).

Anchor Solutions


Solution 1 - Anchor

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

Solution 2 - Anchor

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

$('.service').click(function(e) {
    e.preventDefault();
});

Solution 3 - Anchor

<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>

Solution 4 - Anchor

$('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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionL84View Question on Stackoverflow
Solution 1 - AnchorMyroslavNView Answer on Stackoverflow
Solution 2 - AnchoricktoofayView Answer on Stackoverflow
Solution 3 - AnchorRyanView Answer on Stackoverflow
Solution 4 - AnchorAndreasView Answer on Stackoverflow