Adam Emeryt
Adam Emeryt

Reputation: 1

How can I use jquery to recognize which section the page has scrolled to?

I have a page which is like this:

<nav style="position:fixed;top=0;left=0;width:100px;">
  <a class="one" href="#one">One</a>
  <a class="two" href="#two">Two</a>
  <a class="three" href="#three">Three</a>
  <a class="four" href="#four">Four</a>
  <a class="five" href="#Five">Five</a>
</nav>
<section style="margin-left:120px;height:550px;">
  <a name="one" id="one"></a>
  Content of section one ...
</section>
<section style="margin-left:120px;height:350px;">
  <a name="two" id="two"></a>
  Content of section two ...
</section>
<section style="margin-left:120px;height:750px;">
  <a name="three" id="three"></a>
  Content of section three ...
</section>
<section style="margin-left:120px;height:450px;">
  <a name="four" id="four"></a>
  Content of section four ...
</section>
<section style="margin-left:120px;height:250px;">
  <a name="five" id="five"></a>
  Content of section five ...
</section>

The Navigation is always visible, and when a user clicks a link it is getting .active class in jquery. But when the user scrolls to a page, I want to change the .active link depending on which section is now at the top of the visible window.
I tried to play with $(window).scroll() and $(link.hash).offset().top, but to be honest I have no idea how to manage it to work properly.

Upvotes: 0

Views: 83

Answers (2)

Andreas Louv
Andreas Louv

Reputation: 47099

nice plugin does the trick: http://imakewebthings.github.com/jquery-waypoints/

Upvotes: 0

eyurdakul
eyurdakul

Reputation: 912

You can use the :visible selector of jquery, see this example;

$("section:visible").filter(":last-child").addClass("active");

Upvotes: 1

Related Questions