Picnic Website Code Tutorials

Highlight Current Page With Javascript Tutorial

View Demo

This functionality is "usually" best done CSS or PHP. But sometimes just CSS/PHP can't get the job done. In which case, we can turn to our old friend JS to help us out! An example where javascript would come in handy to highlight the current page is... Suppose you where using JS to swap panels all on the same page. Well, in cases such as those, we'd have to use javascript to give us what we want. I should note though, that statement is not entirely true. You "can" use PHP to do it, but it's a little complicated. This JS method is MUCH easier, and there's nothing wrong with easy! I'm feeling a little lazy today, and the code is pretty self explanatory, so I'll just let it do the talking.

The Code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highlight Current Page With Javascript Example</title>
<style type="text/css">
<!--
* {
	margin:0;
	padding:0;
}
body {
	background:#CCC;
	font:140% "Times New Roman", Times, serif, Arial;
	line-height:1.5;
	font-weight:bold;
}
/* ---------------- #nav --------------- */
#nav {
	width:100px;
	list-style:none;
	margin:100px auto;
}
#nav a {
	color:black;
	text-decoration:none;
	outline:0;
}
#nav a:active, #nav a:focus, #nav a:hover {
	color:red; 
}
#nav a.highlite {
	color:red;
}
-->
</style> 
</head>

<body>
  
<ul id="nav">
  <li><a id="default" class="highlite" onclick="highlite(this);" href="#">Link1</a></li>
  <li><a onclick="highlite(this);" href="#">Link2</a></li>
  <li><a onclick="highlite(this);" href="#">Link3</a></li>
  <li><a onclick="highlite(this);" href="#">Link4</a></li>
  <li><a onclick="highlite(this);" href="#">Link5</a></li>
</ul>

<script type="text/javascript">
var current = document.getElementById('default');

  function highlite(el)
  {
     if (current != null)
     {
         current.className = "";
     }
     el.className = "highlite";
     current = el;
  }
</script> 

</body>
</html>
		

Sponsors

Top Donators

Friends of Mine