Add image with dynamic src in HTML using javascript

Marius
Posts: 55

Add image with dynamic src in HTML using javascript

Hello
Anyone know how to directly display in HTML an image with dynamic SRC, from external URL address, using JavaScript?
To have in html something like:

Code: Select all

<img src='external_url/dynamic_name.jpg' />

Thanks!

Admin
Hello
Try this code:

Code: Select all

<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');

//receives the JPG image name (without extension)
function addImg(imn){
  dimg.innerHTML ='<img src="http://xxx.xxx.xxx/'+ imn +'.jpg'" >';
}
addImg('imgname'); //adds the image imgname.jpg
</script>

Or this:

Code: Select all

<img src='default_image.jpg' id='img1' />
<script>
var img1 = document.getElementById('img1');

//receives the JPG image name (without extension)
function addImg(imn){
  img1.src ='external_url/'+ imn +'.jpg';
}
addImg('imgname'); //adds the image imgname.jpg
</script>

Adv. Posts: 01

Similar Topics