Johns M Tsai
Johns M Tsai

Reputation: 23

How to display dynamic url image in html from which created by javascript

I am trying to display the image directly in HTML through a dynamic link I generated by Javascript.

function dynamicUrl() {
var url = "http://xxx.xxx.xxx" + dynamic_variables + ".jpg";
return url;}

Most of my research, people display image by click on buttons or what I can do for now is link to the image.

<a href="javascript:window.location=dynamicUrl();">test</a>

Anyone know how to directly display the image using the dynamic URL? Thanks!

Upvotes: 2

Views: 13576

Answers (3)

Val
Val

Reputation: 22797

Dynamic create DOM for example:

function dynamicUrl() {
  var url = "https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg";
  return url;
}

var img = document.createElement("img");
img.src = dynamicUrl();
document.body.appendChild(img);

Manipulate DOM to dynamic change img url:

function dynamicUrl() {
  var url = "https://www.62icon.com/client/assets/img/like-icon.svg";
  var img = document.getElementById('imageid');
  img.src = url;
}
<div>
   <p>Image goes here</p>
   <button onclick="dynamicUrl()">Change Image</button>
</div>
<img id="imageid" src="https://is1-ssl.mzstatic.com/image/thumb/Purple111/v4/dd/95/7e/dd957e3a-abd3-da8a-2211-726a67108938/source/256x256bb.jpg" />

Upvotes: 4

CoursesWeb
CoursesWeb

Reputation: 4237

Here is another method:

<div id="dimg">Here add image</div>
<script>
var dimg = document.getElementById('dimg');
function addImg(dv){
  dimg.innerHTML ='<img src="http://xxx.xxx.xxx'+ dv +'.jpg'" >';
}
addImg('imgname');
</script>

Upvotes: 0

Ashan
Ashan

Reputation: 19738

Adding a id for the link element

<a id="link" href="">test</a>

Using click event of link element

var link = document.getElementById("link");

link.onclick = function goToDynamicUrl() {
  var url = "https://image.flaticon.com/teams/new/1-freepik.jpg";
  window.location.href = url;
}

Upvotes: 0

Related Questions