2

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!

3 Answers 3

4

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" />

Sign up to request clarification or add additional context in comments.

1 Comment

@JohnsMTsai you're welcome =) added another example that changes existing img url.
0

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;
}

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.