Page 1 of 1

Add image with dynamic src in HTML using javascript

Posted: 03 Jun 2017, 08:19
by Marius
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!

Add image with dynamic src in HTML using javascript

Posted: 03 Jun 2017, 08:25
by 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>