Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent/stop auto anchor link from occurring

I need to prevent the automatic scroll-to behavior in the browser when using link.html#idX and <div id="idX"/>.

The problem I am trying to solve is where I'm trying to do a custom scroll-to functionality on page load by detecting the anchor in the url, but so far have not been able to prevent the automatic scrolling functionality (specifically in Firefox).

Any ideas? I have tried preventDefault() on the $(window).load() handler, which did not seem to work.

Let me reiterate this is for links that are not clicked within the page that scrolls; it is for links that scroll on page load. Think of clicking on a link from another website with an #anchor in the link. What prevents that autoscroll to the id?

Everyone understand I'm not looking for a workaround; I need to know if (and how) it's possible to prevent autoscrolling to #anchors on page load.


NOTE

This isn't really an answer to the question, just a simple race-condition-style kluge.

Use jQuery's scrollTo plugin to scroll back to the top of the page, then reanimate the scroll using something custom. If the browser/computer is quick enough, there's no "flash" on the page.

I feel dirty just suggesting this...

$(document).ready(function(){

    // fix the url#id scrollto "effect" (that can't be
    // aborted apparently in FF), by scrolling back
    // to the top of the page.
    $.scrollTo('body',0);

    otherAnimateStuffHappensNow();

});

Credit goes to wombleton for pointing it out. Thanks!

like image 561
Jared Farrish Avatar asked Mar 31 '09 23:03

Jared Farrish


3 Answers

This seems the only option I can see with ids:

$(document).ready(function() {
  $.scrollTo('0px');
});

It doesn't automatically scroll to classes.

So if you identify your divs with unique classes you will lose a bit of speed with looking up elements but gain the behaviour you're after.

(Thanks, by the way, for pointing out the scroll-to-id feature! Never knew it existed.)

EDIT:

like image 196
wombleton Avatar answered Sep 20 '22 11:09

wombleton


I know this is an old thread but i found something without the need to scroll. Run this first before any other scripts. It puts an anchor before the first element on the page that prevents the scroll because it is on top of the page.

function getAnchor(sUrl)
{
  if( typeof sUrl == 'string' )
  {
   var i = sUrl.indexOf( '#' );
   if( i >= 0 )
    { return sUrl.substr( i+1 ).replace(/ /g, ''); }
  }
  return '';
};

var s = getAnchor(window.location.href);
if( s.length > 0 )
 { $('<a name="'+s+'"/>').insertBefore($('body').first()); }

Cheers! Erwin Haantjes

like image 29
Codebeat Avatar answered Sep 20 '22 11:09

Codebeat


  1. Scroll first to top (fast, no effects pls), and then call your scroll function. (I know its not so pretty)
  2. or just use a prefix
like image 35
Bebna Avatar answered Sep 17 '22 11:09

Bebna