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

jquery-change-image

Time for some jQuery action!

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

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

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?

OUTPUT

Before

image

After

image




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Unknown said...

hi
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?????