Tuesday, 5 July 2011

Change Css Class of li in ul onclick

Below is the simple and a short code to change or set the background color of item in menu onclick or active tab of menu (i.e. li of ul)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>List Item</title>
<style type="text/css">
ul
{
    list-style-type:none;
    float:left;
    border-bottom: solid 2px Red;
    padding-right:40px;
}
ul li
{
    float:left;
    width:auto;
    padding:8px;
    display:block;
    cursor:pointer;
}
</style>

<script type="text/javascript" language="javascript">

    function checklist(ctrl)
    {
       
        var list = document.getElementById("menu").getElementsByTagName('li');
       
        for(i=0; i<list.length; i++)
        {
            list[i].style.background = '#ffffff';
        }
       
        ctrl.style.background = '#ff0000';
    }


</script>
</head>

<body>
<ul id="menu">
<li onclick="checklist(this);">A Item</li>
<li onclick="checklist(this);">B Item</li>
<li onclick="checklist(this);">C Item</li>
</ul>
</body>
</html>

Screenshot:-



The code is simple.. just copy and paste... Enjoy..

4 comments:

  1. I am a begginer and was searching internet for a long time to find this. Thanks a lot.

    ReplyDelete