1

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.

1

1 Answer 1

2

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>

2
  • Thanks so much, this is perfect. I wasn't aware of the target selector.
    – xhadf
    Mar 4, 2013 at 21:32
  • Do keep in mind that CSS transitions are not compatible with many versions of IE. Same goes for :target. Mar 4, 2013 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.