marchemike
marchemike

Reputation: 3277

updating image source using jquery not working properly

I'm trying to update my image source using jquery. To do it, I am calling .load

function that will return a string which in turn will be used to replace the image source.

srcResult value is new/icon.png:

<script>
 var iconLinkURL = "Users/NewIcon";
 var srcResult = $("#iconImage").children('img').load(iconLinkURL); 


  $("#iconImage").children('img').attr('src', srcResult);
</script>

HTML Side

<a id="iconImage"><img src="old/address.png"></img></a>

What happens is that when the javascript is loaded, the image is loaded like this:

 <a id="iconImage"><img src="[object Object]">new/icon.png</img></a>

Am I missing something hence the issue is persisting?

Upvotes: 1

Views: 129

Answers (1)

BenM
BenM

Reputation: 53198

load() returns an object. If you're not interested in pre-loading, just replace your code as follows:

$("#iconImage").children('img').prop('src', 'Users/NewIcon');

However, if you wish to preload the image, use the following:

var src = 'Users/NewIcon',
    img = new Image();

img.src = src;
img.onload = function() {
    $('#iconImage').children('img').prop('src', this.src);
};

It's worth noting that you will also need to wrap your code in the DOMReady event if you're not doing that already.

Upvotes: 2

Related Questions