Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign img' src dynamically

The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.

<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
    <img src=whatneedtogohere /></div>


  function displayText(text) {
    console.log(text);
    document.getElementById("message").innerHTML=text;
    window.castReceiverManager.setApplicationState(text);
  };
like image 945
EmilyJ Avatar asked Dec 15 '22 00:12

EmilyJ


2 Answers

Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:

<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
    <img src="" id="image" />
</div>

JS:

document.getElementById('image').src = 'http://yourImagePathHere';

See it work here: http://jsfiddle.net/N3rCm/

like image 64
Shomz Avatar answered Dec 17 '22 15:12

Shomz


First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.

Next I would give your image a class if you can

//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);

//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');

myImg.src = imgSrc;
like image 44
Brodie Avatar answered Dec 17 '22 13:12

Brodie