ELias Rahme
ELias Rahme

Reputation: 107

How to load several images in the same place

I have created an html document that uses javascript to connect to xml and get the name of a picture to load using this CSS :

#container {
 width:800px;
}
#left {
    top:10%;
    position: relative;
    float: left;
    width:200px;
    left:30px;
}
#right {
  position:absolute;
  top: 0px;
  right: 300px;
  z-index:-1;
}

And this code:

var TestP = new Array();

function loadImg(n){

TestP[n] = xmlDoc.documentElement.childNodes[n].textContent;
var img = document.createElement('img');
alert(TestP[n]);
img.src = TestP[n];


alert(n);
alert(TestP[n]);
document.getElementById('right').appendChild(img);

A part of the HTML :

<li><a href="#" onClick="loadImg(1)">Part 1</a></li>

The thing is when I first click on the link, everything works well, but when I click another time, I will get two images, each at a different position. I want to have the second image take the exact same place, beeing on top of the first one.

Upvotes: 0

Views: 236

Answers (4)

Tom
Tom

Reputation: 4180

don't create a new image, but replace the src attribute.

first give the image an id, so you can find it:

<img id="myimage" src="..."/>

changing it goes like this:

document.getElementById("myimage").src = "...new source...";

another option:

var TestP = new Array();

function loadImg(n) {
    TestP[n] = xmlDoc.documentElement.childNodes[n].textContent;
    var myImage = document.getElementById("myimage");
    if(myImage != null) {
        myImage.parentNode.removeChild(myImage);
    }
    var img = document.createElement('img');
    img.src = TestP[n];
    img.id = "myimage";
    document.getElementById('right').appendChild(img);
}

Upvotes: 1

untitled8468927
untitled8468927

Reputation: 676

elem = document.getElementById( 'right' );
child = elem.firstChild;
if ( child )
  elem.replaceChild( img, child );
else
  elem.appendChild( img );

Upvotes: 1

pimvdb
pimvdb

Reputation: 154898

Sounds like you just want one image, of which you change the URL each time.

Define in your HTML:

<img id="image">

and use in JavaScript:

var TestP = []; // cleaner way for creating an array

function loadImg(n) {
  TestP[n] = xmlDoc.documentElement.childNodes[n].textContent;

  document.getElementById('image').src = TestP[n];
}

Also note that HTML5 introduces some semantics, one of which being binding event handlers through JavaScript instead of through HTML.

Upvotes: 1

Oriesok Vlassky
Oriesok Vlassky

Reputation: 797

well, you are doing it with .appendChild(). then you call it again and it appends second child. so, you have two options. before you append the second image, remove the old one, OR, just replace it.

Upvotes: 0

Related Questions