Astralis Lux
Astralis Lux

Reputation: 373

Can I pass a URL as a variable?

I have the following script that is not giving me the result I want. JSFiddle link at the bottom.

Note: This is not my image. I grabbed it randomly from imgur.

I expect:

<img src="https://i.imgur.com/MiOeWrk.jpg" style="max-width:800px;">

But I get this, I believe, but I'm unable to write this in a code block while debugging, for some reason.

<img src="http://thisismydomain.com/https://i.imgur.com/MiOeWrk.jpg" style="max-width:800px;">

Here's my script. Please advise:

<div><a href="javascript:viewimage('https://i.imgur.com/MiOeWrk.jpg','video_aba');">Show Image</a></div>

<div id="jsdebug">jsdebug</div>
<div id="video_aba">video_aba</div>

<script>    
function viewimage(ytlink, uid) {
  var imagelink = ytlink;
  document.getElementById("jsdebug").innerHTML = imagelink;
  var uid = uid;
  if (imagelink.length == 0) {
    imageembed = "<strong>Sorry, unable to load.</strong>";
  } else {
    imageembed = "<img src=\"/" + imagelink + "\" style=\"max-width:800px\">";
  }
  document.getElementById("video_aba").innerHTML = imageembed;
}
</script>

https://jsfiddle.net/gde5630h/

Upvotes: 0

Views: 93

Answers (2)

anjaneyulubatta505
anjaneyulubatta505

Reputation: 11695

Your attribution is not correct. href should be replaced with onclick event.

"href" is not used for javascript events. It is used to link the webpages.

javascript events are onclick, onhover, onmouseenter, etc.

function viewimage(ytlink, uid) {
  var imagelink = ytlink;
  var uid = uid;
  if (imagelink.length == 0) {
    imageembed = "<strong>Sorry, unable to load.</strong>";
  } else {
    imageembed = `<img src="${ytlink}" style="width:800px">`;
  }
  document.getElementById("video_aba").innerHTML = imageembed;
  document.getElementById("jsdebug").innerText = imageembed;
}
a {
color: blue;
text-decoration: underline;
cursor: pointer;
}
<div><a href="#" onclick="viewimage('https://i.imgur.com/MiOeWrk.jpg','video_aba');">Show Image</a></div>

<div id="jsdebug">jsdebug</div>
<div id="video_aba">video_aba</div>

Upvotes: 1

hs-dev2 MR
hs-dev2 MR

Reputation: 222

The problem is what your image link coded . It's like this imageembed = "<img src=\"/" + imagelink + "\" style=\"max-width:800px\">";

/ => this will prepend to your current domain url eg.if your domain is localhost it will goes localhost/https://i.sstatic.net/gQ54n.jpg

So remove / from your image link

Upvotes: 1

Related Questions