Toggle Background Color using Javascript
A simple javascript function that toggles the background color of HTML elements
Published Jul 28, 2005 by lobo235This is a simple javascript function I made to toggle the background color of any element that can have a background color. In order for it to work properly, the element has to start out with no background color specified. This javascript function works great by itself or it can be applied to elements using unobtrusive javascript methods as described in my article, Unobtrusive Javascript made easy. To use the function just put the color you want the background to toggle to in place of #FFFF00 in the function. Then for any element you can either set an onclick, onmouseover, onmouseout, or other javascript event to call toggleBgColor(). Here is the function:
function toggleBgColor( elem )
{
var style2 = elem.style;
style2.backgroundColor = style2.backgroundColor? "":"#FFFF00";
} So, lets use the following example to show how the toggleBgColor() function works. In my document I have a table and I want the user to be able to click the rows in the table to highlight them. If they click the row again I want to remove the highlighting. Using the toggleBgColor() javascript function above, this is quite an easy task. For each <tr> tag in the table all I have to do is add the onclick attribute to any rows I want to be toggled as follows:
<table cellspacing="0" cellpadding="5">
<tbody>
<tr>
<th>Date</th><th>Duration</th><th>Activity</th>
</tr>
<tr class="handcursor" onclick="javascript:toggleBgColor( this );">
<td>2005-07-25</td>
<td>1</td>
<td>Bicycling</td>
</tr>
<tr class="handcursor" onclick="javascript:toggleBgColor( this );">
<td>2005-07-26</td>
<td>.5</td>
<td>Jogging</td>
</tr>
<tr class="handcursor" onclick="javascript:toggleBgColor( this );">
<td>2005-07-27</td>
<td>2</td>
<td>Ping Pong</td>
</tr>
</tbody>
</table> Here is the result:
| Date | Duration | Activity |
|---|---|---|
| 2005-07-25 | 1 | Bicycling |
| 2005-07-26 | .5 | Jogging |
| 2005-07-27 | 2 | Ping Pong |
All in all, this is a very simple javascript function that is very useful. If you have any feedback about this article, please drop us a line and let us know.
4 comments for this article.
add this article to del.icio.us!
Other great Web Development and Programming articles on Netlobo.com:Passing information from Javascript to PHP
PHP Application Feature Management
Clean URLs using Apache's mod_rewrite
