October 8, 2011

Javascript simulation of rolling of a dice


Write Javascript code to simulate the rolling of a dice. When the user clicks a button, the result should be the simulation of a dice - a value between 1 to 6 is displayed in the String, "Your roll of the dice displayed 3"

Hint: Math.random(), document.getElementById(), innerHTML, onclick event

Solution


<html>
<head>
<script type="text/javascript">

var rollDice = function() {
   var diceElementNode = document.getElementById("diceValue");
   var diceElementNodeChildren = diceElementNode.childNodes;

   if (diceElementNodeChildren[0] != null) {
      diceElementNodeChildren[0].nodeValue = "The dice value is " + Math.ceil((Math.random() * 6));
   } else {
      var diceTextNode = document.createTextNode("");
      diceTextNode.nodeValue ="The dice value is " + Math.ceil((Math.random() * 6));
      diceElementNode.appendChild(diceTextNode);
   }
}

window.onload = function() {
   document.getElementById("diceButton").onclick=rollDice;
}

</script>
</head>
<body>
<button id="diceButton">Roll Dice</button>
<div id="diceValue"></div>

</body>
</html>

No comments:

Post a Comment