Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I navigate to slightly above an anchor tag?

I know how to navigate to a given anchor tag on a page - what I'm trying to do is link to a part of the page that is 30-40 pixels above the target anchor. The reason for this is that I have a bootstrap navigation that ends up covering part of the relevant content if I like directly to the part of the page with the anchor.

Currently I have this for the link:

%a{:href => root_path + "#how_it_works"} How It Works

and on the page it links to:

.span12#how_it_works

Any thoughts on how I can get the link to navigate to a section of the page that is slightly above the .span12#how_it_works?

like image 789
Cam Norgate Avatar asked Apr 07 '13 01:04

Cam Norgate


1 Answers

You might be able to hack around this by adding some extra padding in your css, but the surest way to do this is with javascript:

$('a[href="#how_it_works"]').on('click',function(e){
  // prevent normal scrolling action
  e.preventDefault();
  // grab the target url from the anchor's ``href``
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
     if (target.length) {
           window.scrollTo(0, target.offset().top - 50); // <-- our offset in px adjust as necessary
      return false;
  }
});

Here's codepen.

This uses a modified version of Chris Coyier's smooth scroll script. I've taken the "smoothness" out of the scrolling, but you could add it back in by animating the scrolltop like so:

   if (target.length) {
     $('html,body').animate({
         scrollTop: target.offset().top + 20
    }, 1000);
    return false;
   }
like image 73
Nick Tomlin Avatar answered Oct 11 '22 04:10

Nick Tomlin