Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent jump on an anchor click?

Tags:

jquery

anchor

I use e.preventDefault(); to disable default anchor behaviour.

Is there a way to prevent only jump action to a target on click?

I tried:

  var hash = window.location.hash;
  var link = $('a');
  $('a').click(function() {
    e.preventDefault();
    hash = "#"+link.attr("href");
  });

But it doesn't work: http://jsfiddle.net/ynts/LgcmB/.

like image 616
A. Z. Avatar asked Jan 06 '13 19:01

A. Z.


People also ask

How would you stop a link from causing navigation when clicked?

One way you can prevent navigation is to implement an click / onclick JavaScript event handler and return false from it. Alternately you can use event. preventDefault() inside the click event's event object passed into the handler too.

How do I stop a Web page from scrolling to the top when a link is clicked?

To stop a web page from scrolling to the top when a link is clicked that triggers JavaScript, we call preventDefault in the link's click handler. document. getElementById("#ma_link").


1 Answers

This is the only solution I could come up with that works consistently across all desktop and mobile browsers with various client UI libraries and frameworks. By getting the window coordinates before scrolling occurs we can revert and maintain the current scroll position.

$('a').click(function (e) {
    var x = window.pageXOffset,
        y = window.pageYOffset;
    $(window).one('scroll', function () {
        window.scrollTo(x, y);
    })
});
like image 142
TaeKwonJoe Avatar answered Sep 30 '22 07:09

TaeKwonJoe