Preventing flickering when clicking on "#" links

On a recent single page website I was working on, I was using something along the lines this for my navigation menu:

1 <ul>
2      <li><a href="#" id="nav1">Navigation 1</a></li>
3      <li><a href="#" id="nav2">Navigation 2</a></li>
4      <li><a href="#" id="nav3">Navigation 3</a></li>
5 </ul>

I attached a click handler to each link, and I was adding a class to the active link and using jQuery to scroll the page, but before the scrolling would take place, the navigation bar would flicker. This was done with a function like:

1 $("#nav1").click(function () {
2      // add class active class
3      // scroll to correct position
4 });

After a little bit of digging I found out that this is caused by the fact that I’m using anchor links for the navigation which have a default action of navigating to the appropriate anchor point. To fix this I updated my click handler to suppress this action like so:

1 $("#nav1").click(function (e) {
2      e.preventDefault();
3      // add class active class
4      // scroll to correct position
5 });

I hope this helps someone else too.