xhadf xhadf - 5 months ago 9
jQuery Question

Change class of <li> when scrolled to

I have a nav set up that when a link is clicked, the page scrolls down to the corresponding item in a list, changing the class of the link when the item is reached.

<nav>
<a href="#one" class="anchorLink">one</a>
<a href="#two" class="anchorLink">two</a>
</nav>


<ul>
<li id="one"></li>
<li id="two"></li>
</ul>


Here is a rather crude example

http://jsfiddle.net/FSk5Q/1/

I would also like to change the background colour of the item once it is reached (preferably fading to a new colour), and then restore it's original class when another item is scrolled to, then changing the next item's class.

Many thanks for an advice. Not too good in the js department.

Answer

You really don't need to complicate this quite so much, simply use, where possible, CSS transitions:

li:target {
    background-color: #f90;
    -moz-transition: all 2s linear;
    -ms-transition: all 2s linear;
    -o-transition: all 2s linear;
    -webkit-transition: all 2s linear;
    transition: all 2s linear;
}

JS Fiddle demo.

body {
  margin: 0;
  padding: 0;
}
nav {
  position: fixed;
  background: #fff;
  width: 10%;
  padding: 50px;
  background-color: rgba(255, 255, 255, 0.4);
  border: 2px solid #000;
}
.highlight {
  background: #b4b4b4;
}
ul li {
  list-style: none;
  margin-bottom: 10px;
  width: 300px;
  height: 500px;
  background: #ccc;
}
li:target {
  background-color: #f90;
  -moz-transition: all 2s linear;
  -ms-transition: all 2s linear;
  -o-transition: all 2s linear;
  -webkit-transition: all 2s linear;
  transition: all 2s linear;
}
li::before {
  content: 'list-element ' attr(id);
  display: block;
  text-align: right;
  font-size: 2em;
  font-weight: bold;
}
<nav>
  <a href="#one" class="anchorLink">one</a>
  <a href="#two" class="anchorLink">two</a>
</nav>


<ul>
  <li id="one"></li>
  <li id="two"></li>
</ul>