Clemen Gronver
Clemen Gronver

Reputation: 181

asp:imagebutton, change image from javascript / jquery

How can i change the image of an image button clientside, on click.

I have tried this:

function changetoDownload(theId) {
   $(theId.id).delay(2000)
   .queue(function (next) { $(theId).attr("ImageURL", "Images/Apps/free.png"); next(); });
}

<asp:ImageButton ID="ImageButton1" OnClick="Button7_Click" OnClientClick="changetoDownload(this.id);" ImageUrl="Images/download.gif" runat="server" />

Upvotes: 1

Views: 5426

Answers (3)

celopez3
celopez3

Reputation: 86

JQuery runs at client side. The reason your javascript isn't working is because the "asp" tag is rendered server side and once displayed on the client side the markup changes to HTML. You are referencing the ImageURL attribute which doesn't exist in HTML it would be the "src" attribute. You can check this by deploying your code and then using "View Source" in your browser.

Upvotes: 1

Pankaj
Pankaj

Reputation: 10095

It is very easy in JavaScript

HTML Code

<asp:ImageButton ID="img" runat="server"  OnClientClick="return abc(this);" />

JavaScript Code

<script language="javascript" type="text/javascript">
function abc(ImageID) {
    var img = document.getElementById(ImageID.id);
    img.src = "Jellyfish.jpg";
    return false;
}

</script>

Upvotes: 1

Jasper
Jasper

Reputation: 76003

//target all `<input type="image" />` elements and bind a `click` event handler to them
$('input[type="image"]').on('click', function () {

    //change the `src` of this element
    $(this).attr('src', 'Images/Apps/free.png');
});

Note that .on() is new as of jQuery 1.7 and in this case is the same as .bind().

I'm not sure how ASP.net will render your button but you can target it using the ID of the element:

$('#MainContent_ImageButton1').on('click', function () {

    //change the `src` of this element
    $(this).attr('src', 'Images/Apps/free.png');
});

You can check the source of your document in a browser to see if that is the actual rendered ID of the ASP button.

Here is a demo: http://jsfiddle.net/jasper/PQ4fp/

Upvotes: 1

Related Questions