Add image with dynamic src in HTML using javascript

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts:107

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 Posts:805
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>

Similar Topics