Skip to content Skip to sidebar Skip to footer

Store A Generated Random Number In A Variable, Then Call That Variable As A Filename To Bring Up An Image. Javascript

So I have a few pictures that I want to randomly generate on a page. the pictures are named 0 - 9 .png Im using a premade function for random number generation. My problem is when

Solution 1:

You need to say document.write("<img src='" + imgNumber + ".png' alt='' />");. Even though imgNumber is an integer, JavaScript will automatically cast it to a string.

Also, you need to put the document.write call before the return statement.

However, like these other people are saying, document.write is probably not the best way to add things to your page. I would recommend getting JQuery or something, and using that for your DOM manipulation.


Solution 2:

There are a few issues with how you're approaching this problem.

First, it is bad practice in modern Javascript development to use document.write. You should be using things like appendChild instead.

Second, you reference imgNumber in a string. This will just use "imgNumber" there, not the contents of the imgNumber variable. For that, string concatenation is one way you could insert it:

"<img src='" + imgNumber + ".png'>"

Here's how I would approach your problem instead. First, place an empty element on the page where you will append your images:

<div id="random-images-here"></div>

Then, somewhere after that element you can have the following Javascript, which is similar to yours:

<script>
    // create a random integer from 0 to maxInt
    var randomInteger = function(maxInt) {
        return Math.floor(Math.random() * (maxInt + 1));
    };

    // append a random image to el
    var showImg = function(el) {
        var imgNumber = randomInteger(9),
            img = document.createElement('img');

        img.src = imgNumber + ".png";
        img.alt = "Image #" + imgNumber;

        el.appendChild(img);
    };

    // grab the element to append images to
    var imgHolder = document.getElementById('random-images-here');

    // place 4 images in the image holder
    for (var i = 0; i < 4; i++) {
        showImg(imgHolder);
    }
</script>

Here's a demo

(Note: I changed the code in the demo slightly to use a site I found with number images.)


Solution 3:

you are writing javascript so you need to edit the source of the image it would work if you are try it in php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example</title>
<script>
        var imgNumber = Math.floor((Math.random()*9)+1);

 document.getElementById("example").src= imgNumber + '.png';


</script>
</head>
<body>
<img id='example' src="" alt="">

</body>
</html>

Solution 4:

document.write is after the return. Its unreachable code.


Post a Comment for "Store A Generated Random Number In A Variable, Then Call That Variable As A Filename To Bring Up An Image. Javascript"