Skip to content

Instantly share code, notes, and snippets.

@angusgrant
Created March 3, 2023 19:30
Show Gist options
  • Save angusgrant/fc54b98462a6214c11369dcc9a383248 to your computer and use it in GitHub Desktop.
Save angusgrant/fc54b98462a6214c11369dcc9a383248 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dice - Web Component</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
</style>
</head>
<body>
<h1>Dice - Web Component</h1>
<roll-dice></roll-dice>
<script>
//Extend the HTMLElement to create the web component
class RollDice extends HTMLElement {
/**
* The class constructor object
*/
constructor () {
//Always call super first in constructor
super();
const btnText = this.innerHTML.trim();
this.innerHTML = `<p>
<button>${btnText ? btnText : 'Roll Dice'}</button>
</p>
<div aria-live="polite"></div>
`
}
/**
* Handle click events
* @param {Event} event The event object
*/
clickHandler (event) {
//get host element
let host = event.target.closest('roll-dice');
//now get the element to update in the DOM.
let updateRegion = host.querySelector('[aria-live=polite]');
// array of dice values
let diceSides = [1,2,3,4,5,6];
if (!updateRegion) return;
//update the Text into the DOM to display the first value
updateRegion.textContent = `You rolled a ${RollDice.#shuffle(diceSides)[0]}`;
}
/*
* This by convention should be called after the UI is loaded
* Runs each time the element is appended to or moved in the DOM
*/
connectedCallback () {
// Attach a click event listener to the button
let btn = this.querySelector('button');
if (!btn) return;
btn.addEventListener('click', this.clickHandler);
}
/**
* Randomly shuffle an array
* https://stackoverflow.com/a/2450976/1293256
* @param {Array} array The array to shuffle
* @return {Array} The shuffled array
*/
static #shuffle (array) {
let currentIndex = array.length;
let temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
}
if ('customElements' in window) {
customElements.define('roll-dice', RollDice);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment