Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically change the color of the selected menu item of a web page?

Tags:

I am new to developing web pages. I am looking to create menus similar to the ones in stackoverflow.com (like Questions, Tags, Users shown above). How do I change the color of the selected menu (for example, the background color of the Question changes to orange when 'clicked')?

I have managed to change the color while hovering (using CSS) as that was simple, but I am having trouble with this.

Can I achieve this effect of changing the color of a clicked item using only CSS?

like image 877
Jeeka Avatar asked Jun 04 '11 21:06

Jeeka


People also ask

How do I change the color of a menu in HTML?

Within your code, you can enter the color name or enter the hexadecimal code for the color. For example, you could enter "red" as the color name, or enter #FF0000, the hexadecimal code for red. For a complete list of supported color names and their hexadecimal codes, click here.

How can change navigation bar background color in HTML?

Use any of the . bg-color classes to add a background color to the navbar. Tip: Add a white text color to all links in the navbar with the . navbar-dark class, or use the .


1 Answers

Set the styles for class active and hover:


Than you need to make the li active, on the server side. So when you are drawing the menu, you should know which page is loaded and set it to:

 <li class="active">Question</li>
 <li>Tags</li>
 <li>Users</li>

But if you are changing the content without reloading, you cannot change set the active li element on the server, you need to use javascript:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
  .menu{width: 300px; height: 25; font-size: 18px;}
  .menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
  .menu li:hover, .menu li.active {
        background-color: #f90;
    }
</style>
</head>
<body>

<ul class="menu">
<li>Item 1</li>
<li class="active">Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>

<script type="text/javascript">

var make_button_active = function()
{
  //Get item siblings
  var siblings =($(this).siblings());

  //Remove active class on all buttons
  siblings.each(function (index)
    {
      $(this).removeClass('active');
    }
  )


  //Add the clicked button class
  $(this).addClass('active');
}

//Attach events to menu
$(document).ready(
  function()
  {
    $(".menu li").click(make_button_active);
  }  
)

</script>
</body>

</html>
like image 65
Anze Jarni Avatar answered Nov 12 '22 10:11

Anze Jarni