Avoid window jump to top when clicking #-links

I've got a page with some questions and answers, the answers are collapsed by default. When they click the question I expand the hidden answer-div. The problem is that when I click these questions, the window jump to the top of the screen. This is not a huge problem, but I find it annoying, because I have to scroll down to the question again.

The links simply looks like this:

<a href="#" id="myID">Myquestion</a>

And I've used jQuery and .click as event-listener.

Are there any simple ways to avoid this, or do I have to use .scroll and finding the coordinates of the question? I'd rather avoid this.

EDIT: I know that I can use anchors to do this, but I'd like to avoid any jumping of the screen at all.


Solution 1:

You need to add preventDefault() to your click handler. This will stop the browser executing it's own link handler, and will only run the code you specify.

Example:

$("#myID").click(function(e) {
    e.preventDefault();
    // Do your stuff
});

Solution 2:

Don't use A tags for tasks that are not navigation-related. It is not semantic markup, and doesn't degrade gracefully. Use buttons instead.

Solution 3:

You can do it very simple: Just add ! in the end of your href:

<a href="#!" id="myID">Myquestion</a>

The alternative jQuery ways are:

$("#myID").click(function(e) {
    e.preventDefault(); // one way 
    return false; // second way prevent default click action from happening
});