16

Is there a way of avoiding the jump when clicking on an anchor link? So that the view does not change.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tomkay
  • 5,120
  • 21
  • 60
  • 92
  • 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 Answers3

25

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/

James
  • 532
  • 3
  • 14
  • 6
    sometimes 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
15

Just use:

<a href="javascript:void(0);">Text</a>
Nirmal
  • 9,391
  • 11
  • 57
  • 81
1

You could use Javascript to prevent the default behaviour of the link, a simple example being:

<a href="#myanchor" onclick="return false;">link</a>
James
  • 13,092
  • 1
  • 17
  • 19