Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
All I know just ID of a Button. Let's It "btnID", Now I need to change the background color of this button using this ID. Is is possible? If possible Please help.
Posted
Comments
Richard C Bishop 17-Sep-13 15:31pm    
You will just need to know the parent of the button and use .FindControl() with the id and create a button object to store that button in. Once you have done that, you can access the properties, backgroundcolor is one of them.

1 solution

First of all, you need to know how to use ClientID with propery ClientIDMode attributes to get the values translated to HTML id attributes the way you want. If you are not clear about this topic, please read:
http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx[^],
http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientid.aspx[^].

The rest is on pure HTML and JavaScript. You need to use the value of the HTML id attribute, to find the element in question.

For the first step, you can create an optional CSS style which you can dynamically add or remove. For purpose of the illustration, let's define two colors, normal and highlight, for example:
CSS
.normal { background-color: silver; }
.highlight { background-color: yellow; }


In JavaScript, you can find the button by ID and change the color by adding, removing or changing the style class in response to some event. The best way to do it I could advise would be using jQuery. Again, just for some working example, let's consider the case when we change the colors when mouse goes on and out of the button:
JavaScript
$(document).ready(function() {
    myButton = $("#someId"); // "#..." is the ID descriptor
    myButton.hover(
        function() { // mouse goes in:
           $(this).removeClass("normal");
           $(this).addClass("highlight");
        }, function() { // mouse goes out:
           $(this).removeClass("highlight");
           $(this).addClass("normal");
    });
}

Please see:
http://api.jquery.com/category/selectors/[^],
http://api.jquery.com/id-selector/[^],
http://api.jquery.com/addClass/[^],
http://api.jquery.com/removeClass/[^],
http://api.jquery.com/hover/[^].

If you need to learn jQuery (highly recommended), please see:
http://en.wikipedia.org/wiki/JQuery[^],
http://jquery.com/[^],
http://learn.jquery.com/[^],
http://learn.jquery.com/using-jquery-core/[^],
http://learn.jquery.com/about-jquery/how-jquery-works/[^] (start from here).

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900