Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 279
Cliff Avatar asked Mar 31 '13 18:03

Cliff


People also ask

Can we change image src using JavaScript?

The cool thing about JavaScript is that you can use it to programmatically alter the DOM. This includes the ability to change an image's src attribute to a new value, allowing you to change the image being loaded.

How do you load a variable in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.

What is IMG src in JavaScript?

Definition and Usage. The src property sets or returns the value of the src attribute of an image. The required src attribute specifies the URL of an image. Note: The src property can be changed at any time.


2 Answers

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

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

like image 190
Mooseman Avatar answered Nov 15 '22 01:11

Mooseman


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.

like image 41
Chris Moschini Avatar answered Nov 14 '22 23:11

Chris Moschini