Monday 17 February 2014

HTML5 - Guessing number game


In this game, we will familiar with properties placeholder of HTML 5 and javascript function querySelector instead of selectElementById in previous version.
<!doctype html>
<title>Number guessing game</title>
<p id="output">I am thinking of a number between 0 and 99.</p>
<input id="input" type="text" placeholder="Enter your guess...">
<button>guess</button>
<script type="text/javascript">
//Game variables
var mysteryNumber = 50;
var playersGuess = 0;
//The input and output fields
var input = document.querySelector("#input");
var output = document.querySelector("#output");
//The button
var button = document.querySelector("button");
button.style.cursor = "pointer";
button.addEventListener("click", clickHandler, false);
function clickHandler()
{
playGame();
}
function playGame()
{
playersGuess = parseInt(input.value);
if(playersGuess > mysteryNumber)
{
output.innerHTML = "That's too high.";
}
else if(playersGuess < mysteryNumber)
{
output.innerHTML = "That's too low.";
}
else if(playersGuess === mysteryNumber)
{
output.innerHTML = "You got it!";
}
}
</script>
 In this game, when users fill textbox a number, and click on guess button, it will return the result of number. Effect of properties placeholder is take a lot of command in javascript in the pass, now it is so easy.
Finally, in this example, we know how to add an event on a button by command button.addEventListener("click", clickHandler, false);

No comments:

Post a Comment