DrStrangeLove
DrStrangeLove

Reputation: 11557

JavaScript images

How do I display the same image on the same page multiple times?

<head>
<Script language="javascript">
function xdf(){

for (i=0;i<10;i++) {

document.write('<b>hello world</b><br>');
}
}

</script>
</head>

this code displays "hello world" 10 times. i would like the same thing but with certain image instead of "hello word"...

Upvotes: 1

Views: 209

Answers (5)

mykhal
mykhal

Reputation: 19895

.. or maybe you'd rather want to define the background, using CSS?

<style type="text/css">
  body { background: url("http://www.google.com/favicon.ico") left repeat-y; }
</style>

(assuming from your previous comment, that you want to have the images in one column on the left edge)

Upvotes: 1

strager
strager

Reputation: 90012

Change:

document.write('<b>hello world</b><br>');

Into:

document.write('<img src="IMAGE FILE NAME HERE.png" alt="TEXT HERE"><br>');

Upvotes: 0

Daniel Vassallo
Daniel Vassallo

Reputation: 344291

You can use document.createElement() to create an img element in JavaScript, and Node.appendChild() to append it to some other node:

var img = document.createElement('img');
img.setAttribute('src', 'my_image.png');
document.getElemenetById('some-div').appendChild(img);

The image will be loaded from the browser's cache if the above is repeated multiple times, appending each new img element to multiple nodes.


As @Matthew Flaschen suggested in a comment below, you could also use the Node.cloneNode() solution instead. You can create your img elment once:

var img = document.createElement('img');
img.setAttribute('src', 'my_image.png');

... and then use img.cloneNode(false) as an argument for appendChild():

document.getElemenetById('some-div').appendChild(img.cloneNode(false));
document.getElemenetById('some-other-div').appendChild(img.cloneNode(false));

Upvotes: 3

mykhal
mykhal

Reputation: 19895

you can clone the images:

<div><img src="http://www.google.com/favicon.ico" id="image" /></div>
<script type="text/javascript">
    n = 5;
    img = document.getElementById("image");
    for (i=0; i<n-1; i++) {
      img2 = img.cloneNode(false);
      img2.id = img.id + "_clone" + i;
      img.parentNode.appendChild(img2);
    }
</script>

Upvotes: 2

Brandon Frohbieter
Brandon Frohbieter

Reputation: 18139

<img src="/path/to/img.png"/> <img src="/path/to/img.png"/>

Upvotes: 2

Related Questions