Overcranked
Overcranked

Reputation: 175

Javascript will not load the pictures

I want to load these banner.png files to the screen but all it prints out is the actual text from the banner array?

function randImg(){
var banner = new Array();

banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}

any thoughts? I think I need to some how add a src but I am not sure how.

Upvotes: 0

Views: 129

Answers (3)

user912695
user912695

Reputation:

The instruction that loads the image should be like this.

Where imgElement is an IMG element.

imgElement.src = randImg();

If you don’t know how to get an IMG element. Give the IMG element an ID attribute and load this like this.

For an IMG element as <img id="myImage" src="" /> Then:

var imgElement = document.getElementById("myImage");
imgElement.src = randImg();

Note.- my answer gives instruction on how to change the source of an IMG element that exists in the DOM (It is recommended to do so). You should NEVER document.write() an element, Neither on demand or when page is loading. That practice has been deprecated and many browsers would delete the whole page contents if you do so.

Upvotes: 0

kroehre
kroehre

Reputation: 1104

My pure javascript DOM manipulation is a little fuzzy (usually use jquery) but something like this should do the trick:

<div id="images"></div>    

<script type="text/javascript">
function randImg(){
       var banner = new Array();

       banner[0] = 'banner1.png';
       banner[1] = 'banner2.png';
       banner[2] = 'banner3.png';
       maxImg = banner.length;
       randNum = Math.floor(Math.random()*maxImg);

       var container = document.getElementById('images');

       var img = document.createElement('img');
       img.setAttribute('src',banner[randNum]);

       container.appendChild(img);
    }
</script>

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77956

Might be too obvious, but...

function randImg(){
    var banner = new Array();

    banner[0] = 'banner1.png';
    banner[1] = 'banner2.png';
    banner[2] = 'banner3.png';
    maxImg = banner.length;
    randNum = Math.floor(Math.random()*maxImg);
    return '<img src="' + banner[randNum] + '" />';
}

Demo: http://jsfiddle.net/AlienWebguy/u7yfq/

Upvotes: 2

Related Questions