Thursday, November 10, 2011

Button-rollover with using RegisterClientScriptBlock Method in

Now let's write a better version of the button rollover by using the RegisterClientScriptBlock method. The problem with the rollover button example from earlier is that when the user's mouse hovered over the button image, the rollover image had to be retrieved from the server in a different request. A better rollover button solution would be where the rollover image of the button is already downloaded and stored in the client's cache so that when the end user hovers over the button, it is immediately displayed. To success this we must create a JavaScript function. The following example shows the JavaScript function as well as the use of the RegisterClientScriptBlock method to get the function onto the page. For this example, the code-behind only needs a Page_Load event for an ImageButton server control.

In .aspx,

<form id="form1" runat="server">
<asp:ImageButton id="ImageButton1" runat="server" ImageUrl="~/Images/img1.jpg">asp:ImageButton>

In code-behind,

protected void Page_Load(object sender, EventArgs e)
ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript",
"<script type='text/javascript'>" +
"if (document.images) {" +
"MyButton = new Image;" +
"MyButtonShaded = new Image;" +
"MyButton.src = 'Images/img1.jpg';" +
"MyButtonShaded.src = 'Images/img2.jpg';" +
"}" +
"else {" +
"MyButton = '';" +
"MyButtonShaded = '';" +
"}" +
ImageButton1.Attributes.Add("onmouseover", "this.src = MyButtonShaded.src;");
ImageButton1.Attributes.Add("onmouseout", "this.src = MyButton.src;");

That' it. :)

No comments:

Post a Comment