Change attributes of HTML elements at runtime
Very often, there is a need to set attributes of HTML elements from code behind. For example, there may be a separate home page for admin and normal business rulers. So, depending upon the logged on user, you may want to change the redirected page from code behind. In the below code, I have added the on click event to redirect to google.com
HTML:
<input type="button" id="inGoogle" value="Go to google.com." runat="server"/>
Code behind:
inGoogle.Attributes["onclick"] = "javascript:parent.location='https://www.google.com'";
Similarly, all other attributes of html element can be changed depending upon your requirement. Below are few of them.
Adding Border to div at runtime
HTML:
<div id="borderDiv" runat="server">
This is border div</div> <asp:Button ID="btnBorder" runat="server" Text="Apply Border class" OnClick="btnBorder_Click" />
CSS:
<style type="text/css">
.borderclass
{
border: 1px dotted green;
}
</style>
Code behind Code
protected void btnBorder_Click(object sender, EventArgs e)
{
borderDiv.Attributes.Add("class", "borderclass");
borderDiv.Attributes.Add("width", "50px");
}
On click of button, I get the bordered div as shown below
Note: Just for explanation, I have set the width attribute separately. Width can be added in the css class itself.
Changing styles
HTML:
<img src="kis.jpg" runat="server" id="imgKrishna" alt="Hare krishna" /> <asp:Button ID="btnImg" runat="server" Text="Remove Blur" OnClick="btnImg_Click" />
Code behind Code
On page load I blur the image by setting the style as
imgKrishna.Attributes["style"] = "display:inline-block;opacity:0.6;filter:alpha(opacity=30);cursor:text";
My screen looks like:
On click of button, this style is removed and new style with only cursor is set through the following code
protected void btnImg_Click(object sender, EventArgs e)
{
imgKrishna.Attributes.Remove("style");
imgKrishna.Attributes["style"] = "cursor:pointer";
}
On button click, screen looks like
Changing Input type to password at runtime
HTML:
<input type="text" name="Password" runat="server” id="password" /> <asp:Button ID="btnPass" runat="server" Text="Show text as Dot" OnClick="btnPass_Click" />
Code behind Code
On click of button, input type is changed to password type so that the user cannot see the typed characters
protected void btnPass_Click(object sender, EventArgs e)
{
password.Attributes["type"] = "password";
}
Hope you got an idea on how to change the attribute of any html element at runtime. This helps a lot in controlling the behavior of your html controls at runtime.Happy coding...