0

I am using bootstrap and jQuery. I have 4 pictures and I only want one to show randomly each time someone hits on a button. What I have tried is to make an array of the images and then use the button to call the function but it does not work. Any idea what I am doing wrong?

This is the button

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
            <button id="button" type="button" class="btn btn-primary">New Photo</button>
        </div>
    </div>
</div>

this is where i want the picture to display

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 text-center">
            <img id="picture">
        </div>
    </div>
</div>

This is my script

<script>
    $(document).ready(function() {
        $("#button").click(function() {
            displayPics();
        });
    });


    function displayPics() {

        var imagesArray = new Array();

        imagesArray = [
            "CM.jpg", "DC.jpg", "MG.jpg", "SW.jpg"
        ]

        var num = Math.floor(Math.random() * (imagesArray.length + 1));
        var img = imagesArray[num];

        $("picture").html("<img src='" + img + "' />")
    }

    window.onload = init;
</script>
0

2 Answers 2

3

Your code needs two fixes.

Fix A: replace this:

var num = Math.floor(Math.random() * (imagesArray.length + 1));

With this:

var num = Math.floor(Math.random() * imagesArray.length);

This is needed because in the original code your random number will range from 0 to 4, instead of the desired 0 to 3.

Fix B: replace this:

$("picture").html("<img src='" + img + "' />")

With this:

$("#picture").attr("src", img);

This is needed because to select by id you need to add a #, and you need to change just the src attribute, so using attr is the way to go.

Sign up to request clarification or add additional context in comments.

Comments

-1
$("picture").html("<img src='" + img + "' />");
$("#picture").attr('src',img);

you lost html selector.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.