Skip to content

Instantly share code, notes, and snippets.

@matthewoestreich
Last active May 12, 2020 01:12
Show Gist options
  • Select an option

  • Save matthewoestreich/d4e2c03c28413904ac8cbfaac74cf6d6 to your computer and use it in GitHub Desktop.

Select an option

Save matthewoestreich/d4e2c03c28413904ac8cbfaac74cf6d6 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<body>
<!-- Try to put all script tags at the bottom of the <body>-->
<!-- The `event` argument in `rollDice(event)` is a special variable name. It contains data about the event,
which we can access in our function. If you tried to use `rollDice(xyz)`, event data would not be passed. -->
<button id="dice-roller" onclick="rollDice(event)">Roll Dice</button>
<!--Uncomment the line below, and remove the line above, to test with assigning event handlers programmatically-->
<!-- <button id="dice-roller">Roll Dice</button> -->
<h4 style="margin: 10px 0 0 0">Result:</h4>
<p id="dice-results" style="margin: 0"></p>
<script>
// This needs to be converted into a function so you can call it over and over without having to refresh the page.
/**
const rollDice = Math.floor(Math.random() * 6) + 1;
*/
// You could also use an arrow function if you wanted, but to keep it simple:
function rollDice(event) { // An event object is passed to Whichever function we use in the `onclick` attribute
console.log(event); // Open your console to view what this event object contains (some useful stuff here)
// In order to render our results, we need to get the element where we wish to place them.
// Using `document.write` will write a brand new page, thus overwriting our existing html.
const resultsEl = document.getElementById("dice-results");
const result = Math.floor(Math.random() * 6) + 1;
resultsEl.innerHTML = result;
/**
document.writeln(result);
*/
}
// If you didnt want to use the `onclick` attribute within the <button id="dice-roller">, you could programmatically set the `onclick` event handler.
// To test this, see line 7, and remove lines 35 and 41
/**
const rollerEl = document.getElementById("dice-roller");
rollerEl.addEventListener('click', event => { // Just like when using the `onclick` attribute, we are passed an event object
rollDice(event);
});
*/
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment