PHP Ferrari
PHP Ferrari

Reputation: 15664

Replace images in a DIV using JavaScript

I want to show different images in a DIV, the turn of an image depend on a random number. The image name is like 1.gif, 2.gif, .. 6.gif

to do that I coded

var img = document.createElement("IMG");
img.src = "images/1.gif";
document.getElementById('imgDiv').appendChild(img);

but it does not replace the old image how ever it add an another image right in the bottom of first image.

syntax for DIV is:

<div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>

may u halp me ?

Upvotes: 1

Views: 20503

Answers (4)

John
John

Reputation: 1540

I would not recommend changing the src of the element in question. That would cause a lag in the display of the next image while the browser downloads the next image. If you have a set number of images you would want to preload them the way you are doing so now.

If you have the following code:

 <div id="imgDiv" style="width:85px; height:100px; margin:0px 10px 10px 375px;"></div>

You can do this:

<script type="text/javascript>
     var nextImage = document.createElement("img");
     nextImage.src = "your source here";

     document.getElementById("imgDiv").appendChild(nextImage);
</script>

Now that you have an image in place you can use the replaceChild() method:

var imageDiv = document.getElementById("imgDiv");
imageDiv.replaceChild(nextImage, imageDiv.childNodes[0]);

Upvotes: 1

heisenberg
heisenberg

Reputation: 9759

var img = document.createElement("IMG");
img.src = "images/1.gif";
var oldImg = document.getElementById('oldImg');
document.getElementById('imgDiv').replaceChild(img, oldImg);

Upvotes: 5

Paul Kearney - pk
Paul Kearney - pk

Reputation: 5543

var dv = document.getElementById('imgDiv');

// remove all child nodes
while (dv.hasChildNodes()) { 
    dv.removeChild(dv.lastChild); 
} 

var img = document.createElement("IMG"); 
img.src = "images/hangman_0.gif"; 
dv.appendChild(img); 

Upvotes: 3

Quentin
Quentin

Reputation: 944550

If you want to replace an element, you need to use replaceChild, not appendChild.

Upvotes: 0

Related Questions