Is there a way of avoiding the jump when clicking on an anchor link? So that the view does not change.
-
Can you show us an example of the "jumping" code? – Soufiane Hassou Jan 31 '12 at 11:36
-
if you don't want the view to change, why have an anchor link? Please clear this out. – Joeri Hendrickx Jan 31 '12 at 12:18
-
I know this is super old, but to answer @JoeriHendrickx sometimes this is not an option. For instance I do A/B split testing which requires modifications to be made to a clients page after load. I cannot edit their original code but must change the behaviour to determine through data if it should be done or not. This question is 100% valid. – Xandor Oct 04 '19 at 16:06
3 Answers
The most semantic and meaningful approach to this problem would be to handle the onclick event from within JavaScript. Ideally this file would be best to be stored in a seperate file, however, including a in-line script within your problem file would suffice. Here's how i'd recommended approaching this problem if your already using a JavaScript library like jQuery.
Assign an ID
Include an id attribute to your anchor so it's able to be selected using jQuery:
<a href="#anchor" id="mylink" title="Title Here">Link Text</a>
Bind click event
From within your JavaScript file / in-line script include the following:
$('#mylink').click(function(event) {
// This will prevent the default action of the anchor
event.preventDefault();
// Failing the above, you could use this, however the above is recommended
return false;
});
The method above is explained in full using the jQuery API websites: http://api.jquery.com/event.preventDefault/

- 532
- 3
- 14
-
6sometimes you want to disable the jump and carry out all other default behavior such as appending #anchor to the location without a page reload. event.preventDefault() alone will not work. – Nicholas Jun 16 '17 at 09:58
Just use:
<a href="javascript:void(0);">Text</a>

- 9,391
- 11
- 57
- 81
-
1I marked this down cos this: http://stackoverflow.com/questions/2321469/when-do-i-need-to-specify-the-javascript-protocol – matpol Nov 11 '13 at 16:40
-
2
You could use Javascript to prevent the default behaviour of the link, a simple example being:
<a href="#myanchor" onclick="return false;">link</a>

- 13,092
- 1
- 17
- 19
-
the positon of the divs with the id does not change when I use your snippet – Tomkay Jan 31 '12 at 11:45
-
2
-
1obviously it does the job on stopping jump but also stops the event from happening – Samuel Ramzan Aug 10 '16 at 23:39