Lesson 15: Hiding and Showing Elements
When developing a game, you will often times want to make elements appear and dissappear. One way of doing this is to change the elements location. We did this in the Shooting Monkeys project. You can always move an element far off the screen to make it dissappear. However, there are more elegant solutions than this which you will learn in this lesson.
1. First, make the green "GO" button do something. Locate the btnGo div in the HTML and add an onclick to call a function named go().
Now a message should appear when the button is pressed.
Later we will modify the code to have the computer randomly select rock, paper, or scissors. However, we don't want the player to be able to press the GO button until they have first selected rock, paper, or scissors themselves.
3. One way to ensure the player selects rock, paper, or scissors before they press the button is to hide the button until they have done so. We can do this in the CSS by setting the btnGo visibility property to hidden.
4. If you have not done so already, declare btnGo as a global variable and then set it equal to the btnGo div element after the page is finished loading.
6. Try it out. When the page loads, the GO button should not be visible but should appear once the a selection is made. Pressing the GO button will still display a message.
Note that just as you can dynamically (while the game is running) change the visibility property of an element to visible, you could also dynamically change it to hidden. This comes in handy when you want something that is visible to dissappear.
The visibility property works for hiding and showing HTML elements. However, it has some drawbacks since the element is still there, but just invisible. This will give you problems in many instances, such as when you are testing to see if two elements are colliding. To truly remove the element from the gameScreen, you can use the display property instead of the visibility property.
7. In the CSS sytle for #btnGo, replace the visiblity: hidden; with display: none;.
9. Try it out again. The function should work the same.
To avoid strange things happening in your game due to the presence of invisible elements, use the display property to hide and show elements instead of the visibility property.