0

I want to achieve smooth scrolling to an anchor with jQuery. I found some solutions, however, they're all based on the fact that the link to the anchor looks like this:

<a href="#anchor-id">TEST</a>

In my scenario, the links look like this:

<a href="some-page#anchor-id">TEST</a>

I have a global navigation-bar that has the link to "some-page" and hovering the menu-entry opens a dropdown inlcuding the links to the anchors on that page.

I found the following script online which works for regular anchor links <a href="#...">:

$('a[href^="#"]').bind('click.smoothscroll', function (e) {
   e.preventDefault();

   var target = this.hash,
   $target = $(target);

   $('html, body').stop().animate({
      'scrollTop': $taeget.offset().top-60 
   }, 4000, 'swing', function () {
      window.location.hash = target;
   });
});

The link to the fiddle: http://jsfiddle.net/2nT8M/5/

The fiddle doesn't seem to work, however the code does work on my website...

My questions:

  • How can I get the script to work in the fiddle (obviously)?
  • Is it possible to use links that include more than just the anchor ID, as needed in my scenario?
paelzer
  • 115
  • 2
  • 11

1 Answers1

0

This is a working fiddle: http://jsfiddle.net/2nT8M/7/

if you want to scroll to an element with an id equal to the #-part for your anchor you can access it like this:

HTML:

<div id="one"><a class="link" href="da#test">TEST</a></div>
<a id="test">ANCHOR</a>
<div id="two"><a class="link" href="ws#test2">TEST2</a></div>
<a id="test2">ANCHOR</a>

Just give an element (in this case ANCHOR) the same ID as your #-part for your href. Also give all clickable anachors a class="link" e.g.

If you check my fiddle you see the following JS:

$('.link').on('click', function(event) {
  event.preventDefault();
  var target = $(this).attr('href');
  target = $('#' + target.split('#')[1]);
  if( target.length ) {
    $('html, body').animate({
        scrollTop: target.offset().top
    }, 1000);
  }
});

like this its getting the #-Part of every anchor you click and scroll to the element with the same ID.

Some details:

target.split('#')[1]

This part takes the href string saved in target before and splits it in 2 parts at '#'. the first part for the first anchor is 'da' and the 2nd part is 'test'. You want 'test' therefor you access it with [1] (its an array).

Now all whats left to do is put a '#' in front of it and use it as a selector:

target = $('#' + target.split('#')[1]);

$('#test') is now your target you want to scroll to.

gulty
  • 1,068
  • 1
  • 8
  • 14