How to display active menu using javascript ?
What does the code do?
1. Onclick of the <a> it call function called selected();
2. Selected function will identify the ID menu and will store in var lilist
3. If store all the the <a>
4. Then you loop through all the stored <a> and remove the class name.
5. obj.className=”red”; assigned the class=”red” to the clicked <a>
Copy past the below code and test it.
<html>
<head>
<title> new document </title>
<meta name=”generator” content=”editplus” />
<meta name=”author” content=”" />
<meta name=”keywords” content=”" />
<meta name=”description” content=”" />
<style>
li{display:inline;padding:0 10px;}
.red{color:#fff;background:red;}
</style>
</head>
<body>
<ul id=”menu”>
<li><a href=”#” class=”red” onclick=”selected(this)”>Menu1</a></li>
<li><a href=”#” onclick=”selected(this)”>Menu2</a></li>
<li><a href=”#” onclick=”selected(this)”>Menu3</a></li>
<li><a href=”#” onclick=”selected(this)”>Menu4</a></li>
</ul>
<script>
function selected(obj){
var lilist = document.getElementById(‘menu’);
var alist = lilist.getElementsByTagName(‘a’);
for (i=0; i<alist.length; i++ )
{
alist[i].className=”";
}
obj.className=”red”;
}
</script>
</body>
</html
No comments yet
Leave a reply