Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid window jump to top when clicking #-links

Tags:

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.

like image 894
OptimusCrime Avatar asked Nov 23 '11 10:11

OptimusCrime


People also ask

How do I stop clicking links from jumping to top of page?

Just use "#/" instead of "#" and the page won't jump. This need to be the best answer.

How do I make a link not clickable?

In order to disable a HTML Anchor Link (HyperLink), the value of its HREF attribute is copied to the REL attribute and the value of HREF attribute is set to an empty JavaScript function. This makes the HTML Anchor Link (HyperLink) disabled i.e. non-clickable.

How do I stop scrolling when scrolling a div element CSS?

mouseleave(function() { $('body'). bind('mousewheel DOMMouseScroll', function() { return true; }); }); This is stopping all scrolling where as I want scrolling to still be possible inside the container.


2 Answers

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 }); 
like image 157
Rory McCrossan Avatar answered Sep 28 '22 12:09

Rory McCrossan


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.

like image 24
Jonas Høgh Avatar answered Sep 28 '22 11:09

Jonas Høgh