1

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?

2
  • use $('').prop('src','url of image''); Commented May 22, 2018 at 7:53
  • <img src="old/address.png"/> not <img src="old/address.png"></img> Commented May 22, 2018 at 7:54

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.