2

I've a query: is it possible to disabled browsers default action on links such as this example?

I am not talking about disabling click event on Anchor tag( PART 123) using event.preventDefault()

What I am trying to do : There is TOC at the beginning of page with name links (#part-) to different part of page. I can easily disable click event on each link using :

$("a.namedLink").click(function(event) {
  event.preventDefault();

  //and do whatever I want to, like animated scroll then moving the dock-able header using jQuery Affix plugin
}); 

But, if someone copies the link or directly opens it by using the URL itself (link), the code above won't work because nothing has been clicked.

I've checked couple of examples, but, they all talk about same page and #click event, like this Stackoverflow thread Scroll to a div using jquery and others:

link1

link2

Please let me know if we can do it and more importantly, if we should do it.

Thanks

Alyona Yavorska
  • 569
  • 2
  • 14
  • 20
Ravish
  • 2,383
  • 4
  • 37
  • 55

2 Answers2

2

You can scroll to an anchor point using:

$(document).scrollTo("a[name='namedLink']");

You can also check the hash location on page load if the user hits the page directly with a hash:

$(function() {
  var hash = window.location.hash.substring(1, window.location.hash.length);
  if(hash != "") {
    $(document).scrollTo("a[name='"+hash+"']");
  }
});

Should you? It's entirely up to you. It would be like re-inventing the wheel just to make it red, even though not everyone likes red.

As pointed out, the very useful scrollTo() method is actually a plugin and not built into jQuery. It can be found here: http://demos.flesler.com/jquery/scrollTo/

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 1
    I think `scrollTo` is a standalone plugin, that doesn't come with jQuery. If so, you should mention that. – Pavlo Jul 16 '13 at 12:07
  • @PavloMykhalov Good point, updated answer to reflect this – CodingIntrigue Jul 16 '13 at 12:11
  • Thanks @Blade0rz, let me try a poc with what you are suggesting, but, I think http://flesler.com/jquery/localScroll/#section5c is somewhat closer to I need. – Ravish Jul 16 '13 at 13:08
0

You could do something like:

$(function () {
  window.scrollTo(0,0);
});

to bring the user back to the top after the page has loaded. This will potentially mean the page jumps twice, however.

rjmunro
  • 27,203
  • 20
  • 110
  • 132