jQuery: Change ASP.NET Image Source at Runtime

In this post, we will see a quick tip of how to change the source of an ASP.NET Image at runtime using jQuery.

Create a new website. Create two folders called Scripts and Image. In the scripts folder, download the latest jQuery minified file. In the Image folder, add two different images of the same size. I have added dnc.png and devc.png.

In the Default.aspx page, add a reference to the jQuery file. Now add an ASP.NET Image Control pointing to one of the images and a button control using which we will change the image source at runtime. Here’s how the markup will look like


Time for some jQuery action!

In the <head> section, add the following code:

<script type="text/javascript">
    $(function () {
        $("#btnLogo").on("click", function (e) {
            $("#imgLogo").attr("src", "image/dnc.png");
            $("#btnLogo").attr("disabled", "disabled");

The code is pretty simple. We are using the new .on() function introduced in jQuery 1.7 to attach the click event to the button. We have provided an anonymous handler function at the point of the .on() call. The first line prevents the default form submission, the second line updates the image source and the last line disables the button control.

You must be wondering why haven’t we used .bind() here. To know more, read my post jQuery 1.7: What happened to live and die?






Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

mohammed rafi said...

the code working fine but when i tried to get the imageurl property of asp:image control through ID it is returns the same value means the original that we initialized but i need jquey updated Imageurl how to get it?????