Arran Scott
Arran Scott

Reputation: 173

Scroll down to a certain amount of pixels using jQuery

Can you scroll down a page to a certain pixel using jQuery?

I'm building a website that has a fixed navigation bar when scrolling and when a button is clicked it will scroll to a certain anchor point using the jQuery smooth scroll plugin.

The problem is that the navigation bar overlaps the section so it cuts half of the text off.

With the increasing number of jQuery animated websites I'm sure someone must have had this issue before but I can't seem to find an answer.

I've installed the Smooth scroll plugin on the Wordpress website in question and have this code inside the section:

<div id="web"></div>, <div id="app"></div>, <div id="seo"></div>

There is three sections in total that each button should scroll to.

Website url: www.gogoblondie.com

Upvotes: 5

Views: 8708

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206131

No need to use strange plugins ;)
This should give you an idea:

LIVE DEMO

  <nav>
    <ul>
      <li><a href="#web">WEB</a></li>
      <li><a href="#app">APP</a></li>
      <li><a href="#seo">SEO</a></li>
    </ul>
  </nav>  

  <div id="web" class="page" style="margin-top:200px;">WEB</div>
  <div id="app" class="page">APP</div>
  <div id="seo" class="page">SEO</div>

CSS:

nav{ 
  position:fixed;
  top:0px;
  width:100%;
  height:200px;
  background:#cf5;
  z-index:2;
}
.page{ 
  position:relative;
  min-height: 800px; 
}

jQ:

var navHeight = $('nav').outerHeight();

$('nav a').click(function( e ){
  e.preventDefault();
  var myHref = $(this).attr('href');
  var newPos = $(myHref).offset().top;
  $('html, body').stop().animate({scrollTop: newPos-navHeight}, 1300);
});

Upvotes: 2

nullability
nullability

Reputation: 10675

scrollTo is a nice jQuery plugin that will let you scroll to an element with an offset.

Upvotes: 1

Related Questions