OnMouseOver Effects Within Content Place Holder When Using Master Pages

On pages that don't use a master page you can use JavaScript to access an object by using it's id. This no longer becomes possible when using master pages since the id of a control within the Content Place Holder is altered to include something along the lines of "ctl00_ContentPlaceHolder1_". To access the controls id we need to use the controls "ClientId" property.

In this example we have placed a mouseover effect on an ImageButton control:

<asp:ImageButton ID="ImgBtn" runat="server" />

The 2 images used are happy.jpg and sad.jpg

The page load code would be:

protected void Page_Load(object sender, EventArgs e)
{
ImgBtn.ImageUrl = "sad.jpg";
ImgBtn.Attributes.Add("onmouseover", "document.getElementById('" + ImgBtn.ClientID + "').src='happy.jpg'");
ImgBtn.Attributes.Add("onmouseout", "document.getElementById('" + ImgBtn.ClientID + "').src='sad.jpg'");
}

Hover your mouse over this image to see it change:-

Note that within the page load we still need to set the ImageUrl property of the control otherwise we wont see any image until we hover our mouse over the area.

We can use the same method for the Image control.