10

I have a JavaScript Image object that I load dynamically with jQuery.

What I want to do is change a <img /> image with one stored on my Image object. How should I do this?

Note: I want to avoid changing the source of my <img /> tag as it downloads it again from the server, and I already have the image stored in my image object

4
  • Have you tried $(image)? Images are usually cached, so loading the same image twice won't download it twice. Commented Mar 10, 2013 at 21:46
  • 1
    I don't get it. Could you explain a bit more? I already know what $(image) does, but I have the image stored in a JavaScript Image object, and I want to avoid changing the src as I don't want to download the image every time I change it Commented Mar 10, 2013 at 21:47
  • 1
    Wrap your image object in the jQuery function. Images are cached, so re-downloading it usually doesn't make a difference. Commented Mar 10, 2013 at 21:48
  • I think the Image object only stores a reference to the image, not the image it's self. Commented Mar 10, 2013 at 21:50

4 Answers 4

11

You mean

$('#imageToChange').replaceWith(imageObject)

?

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

4 Comments

How can I do the same thing with only javascript and without jQuery?
@S.P.H.I.N.X - ask a question - you mean document.querySelector("img").src=imageObject.src?
No, I want to set a javascript object (myImage = new image ()) into a document html like` document.querySelector("img")=myImage`.
That does not make much sense to me. But ask a new question
2

New Image object:

var Image_off = new Image();
Image_off.src = 'first.jpg';

image src change with jQuery:

$("#my_image").attr("src",Image_off.src);

Comments

1

With jQuery... have both images already on your page and show or hide either one, based on a logical condition.

1 Comment

Hmm, this might actually answer the underlying question rather than what the OP thought was the issue :)
0

Make your new image in javascript memory, and then append it after the original image, then remove the original. You may also wish to cache the original before removing it in case you would like to re-use it.

html

<img id="replace" />

js

var img = new Image();
img.src = "someUri.png";
$("#replace").after(img);
$("#replace").remove();

6 Comments

How is this different than $("#replace").prop('src', 'someUri.png')?
Easier with $('#replace').replaceWith(img);, just saying.
@ExplosionPills - The OP said not to change the src is why I went that route.
@FabrícioMatté my thought exactly :)
@FabrícioMatté - I left it separate in case the OP wanted to save the replaced image before removing it (perhaps with clone).
|

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.