Neo
Neo

Reputation: 167

html image src call javaScript variable

this is my code: I want to ask

<script type="text/javascript">

var total = 4;

</script>

How can I do this?

<img src="img/apple_" + total + ".png" id="imageBox"/>

I've been try to use call function and document.onload but it's not work at all, can somebody save me?

Upvotes: 12

Views: 77102

Answers (4)

jcubic
jcubic

Reputation: 66490

You need to add html in JavaScript like this:

<div id="foo"></div>
<script type="text/javascript">

var total = 4;
document.getElementById('foo').innerHTML = '<img src="img/apple_' + total + '.png" id="imageBox"/>';
</script>

Upvotes: 5

Sunil Kumar
Sunil Kumar

Reputation: 1381

window.onload = function() {
  var total = 4;
  document.getElementById('imageBox').src = 'img/apple_' + total + '.png"';

};
<img src="" id="imageBox"/>

Upvotes: 2

kp singh
kp singh

Reputation: 1460

I am supposing you just want to update the image src with javascript.

document.getElementById('imageBox').src = "img/apple_" + total + ".png";

Upvotes: 12

kockburn
kockburn

Reputation: 17616

Here is a clean way to do this.

Demo

var create_img_element = function(total, targetId){
    //create the img element
    var img = document.createElement('img');
    //set the source of the image
    img.src = 'img/apple_' + total + '.png';
    //add the image to a specific element
    document.getElementById(targetId).appendChild(img);
}

create_img_element(5, 'foo');

Upvotes: 1

Related Questions