In this game, we will familiar with properties placeholder of HTML 5 and javascript function querySelector instead of selectElementById in previous version.
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.<!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 variablesvar mysteryNumber = 50;var playersGuess = 0;//The input and output fieldsvar input = document.querySelector("#input");var output = document.querySelector("#output");//The buttonvar 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>
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