How to Change an Image in Asp.Net With JavaScript

Save

The ASP.NET framework provides Web developers with the tools to create dynamic websites. The controls used in an ASP.NET website are executed on the server. This means the control is unavailable to the JavaScript language, which runs on the client's computer. Microsoft provides a way to "hook" a JavaScript function to an ASP control such as an image. The JavaScript function is added to the image in the ASP code, which is then used to switch the image when the user hovers the mouse over the element.

  • Add your image control to your ASP Web page. The following code is an example of an image server control in ASP:

    <img runat="server" id="TheImage" src="image1.jpg">

    Replace "image1.jpg" with an image on your website.

  • Open your ASP code-behind file and locate the "Page_Load" event. This block of code is usually at the top of the code-behind. Within the event block, start the code using the following code:

    string javascript = "this.src=\"newFileImage.jpg\"";

    This code creates a string for the JavaScript command that switches the image. The code changes the source of the image to the "newFileImage.jpg" file.

  • Add the JavaScript code to the image control. The following code adds the JavaScript code to the image created in Step 1:

    TheImage.Attributes.Add("onmouseover", javascript)

    This code changes the image for the Web page control with the user hovers the mouse over the element. This trigger happens using the "onmouseover" event, which is indicated in the above code.

References

  • Photo Credit internet image by Soja Andrzej from Fotolia.com
Promoted By Zergnet

Comments

You May Also Like

Related Searches

Check It Out

Geek Vs Geek: Robot battles, hoverboard drag race, and more

M
Is DIY in your DNA? Become part of our maker community.
Submit Your Work!