usera5519
usera5519

Reputation: 23

Image reveal game javascript

Hi I am new to JavaScript and have to make a game.

My game involves finding animals that are hiding behind objects in the space of 60 seconds. All my objects are images and I have created them with divs.

I need to hide the image of the animal behind the object so when the player clicks on the object the animal appears. I was going to use an alert but not sure if that's the best approach.

Example of code: Html:

<div id ="clown"> 
  <img src="clown.png" width="300" height="250">
</div>

Javascript: clown = document.getElementById('clown')

Upvotes: 2

Views: 1473

Answers (2)

super
super

Reputation: 2328

You can achieve this by changing the selected image display from none to block. see HTMLElement.style and display property for further info, Check this:

CSS

.image-wrapper {
    width: 300px;
    height: 250px;
    background-color:#00ff21;
    float:left;
    margin:2%;
}

.image-wrapper img {
    display: none;
    width: 300px;
    height: 250px;
}

HTML

<div id="clown" class="image-wrapper">
    <img src="clown.png" width="300" height="250" />
</div>
<div id="bird" class="image-wrapper">
    <img src="bird.png" width="300" height="250" />
</div>

JavaScript

var divs = document.querySelectorAll(".image-wrapper");
for (i = 0; i < divs.length; i++) {
    var div = divs[i];
    div.onclick = function () {
        var img = this.getElementsByTagName('img')[0];
        if (img != undefined) {
            img.style.display = "block";
            console.log(img)
        }
    }
}

Here is the demo

Upvotes: 1

bibekdahal
bibekdahal

Reputation: 74

So as I understand, you want two types of images displayed: object and animal, where animal is hidden by default and is revealed when the object is clicked.

This can be done using css and javascript as shown in example below.

<style>
#object .animal {
    position: absolute;
    left:0;
    top:0;
    visibility:hidden;
}
</style>


<div id="object">
<img class="animal" src="animalimgsrc">
<img src="objimgsrc">
</div>


<script>
document.getElementById("object").onclick = function(){
    document.getElementById("object").getElementsByClassName("animal")[0].style.visibility = "visible";
};
</script>

I guess, you need to make "object" class instead of id, if you want multiple objects.

Upvotes: 1

Related Questions