vendredi 26 février 2016

Change image by id

I'm totally new in JavaScript. I need to change image randomly on click. Here is my code. What's wrong? I'm trying to make a dice game where you roll a dice and a image value pops. I only get the number change on screen when i click on image, but the image changes from 1.jpg to 6.jpg and thats all.

<!DOCTYPE html>
<hml>
<body>


<img id="myImage" onclick="changeImage()"  src="1.jpg" width="100" height="100">

<p id="pl" ></p>

</body>

<script>
function myFunction() {
    var x = Math.floor((Math.random() * 6) + 1);
    document.getElementById("pl").innerHTML = x;
}

</script>

<script>
function changeImage() {
    var image = document.getElementById('myImage');
    var pl;

    pl = myFunction();
    if (pl == 1) {
        image.src = "1.jpg";
    } else if (pl == 2) {
        image.src = "2.jpg";
    } else if (pl == 3) {
        image.src = "3.jpg";
    } else if (pl == 4) {
        image.src = "4.jpg";
    } else if (pl == 5) {
        image.src = "5.jpg";
    } else {
        image.src = "6.jpg";
        }
}
</script>


</html>




Aucun commentaire:

Enregistrer un commentaire