How do I add a javascript variable to HTML image src tag

22,897

Solution 1

var randomImage = 1 + Math.floor(Math.random() * 20);    
var imgName = randomImage+".png";
$("#randImg").attr("src",imgName);

Demo: http://jsfiddle.net/a9Ltw/

Solution 2

Spelling it out a bit to help teach:

On your page you'd have something like this:

<img id=randomImage />

And probably in the head to hide the image until you've picked one to load, this:

<style>
#randomImage {
    width: 400px; height: 200px; /* or whatever the dimensions are */
    visibility: hidden;
}
</style>

Then in your Javascript:

var ordinal = 1 + Math.floor(Math.random() * 20);
$('#randomImage').css('visibility', 'visible').attr('src', ordinal + '.png');

So the HTML lays out the img tag, and some early CSS sets its dimensions and hides it so there's no ugly broken image icon etc in some browsers - just a blank space.

Then eventually the Javascript loads and runs, determining a random ordinal. The second line of Javascript calls jquery to make the img visible and set its src attribute to the random image.

Solution 3

$(document).ready(function() {
    var randomImage = 1 + Math.floor(Math.random() * 20),    
                img = randomImage + ".png";

    $("#randImg").attr("src", img);
});

Solution 4

Just add some default image to img tag to prevent displaying nothing if user has disabled JavaScript, and then in jQuery use $("#randImg").attr("src", randomImage + ".png");

Share:
22,897
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I know this answer is out here, but I have been unable to find it (or at least recognize it when I saw it!). I'm a relative noob to jquery, so bear with me please.

    Problem:

    I have 20 images, named 1.png through 20.png. I would like a different image to display randomly each time a user clicks a button.

    What's working:

    My javascript code to generate the random number looks like this:

    var randomImage = 1 + Math.floor(Math.random() * 20);
    

    What's not...

    What I'm trying to do is pass the result of that to my HTML document as the name of the image, so that is reads something like this:

     <img id="randImg" class="img_answer" src="randomImage.png">
    

    I tried concatenating, but can't seem to figure this out. Do I need to create a function that affects the img ID or class? Can anyone point me to the cleanest way to do this?