D&D (fantasy) Dice Roller
About this project:
This project was the result of me wanting a halfway decent online dice roller that could cover all of the standard dice used in role playing games (d4, d6, d8 , d10, d12, d20, d100). It's simple, but looks alright and the code is fair.
Works best when viewing code in JS Bin
The HTML & CSS►
This page consists of a number of buttons with event listeners tied to them. All of the buttons are inline-block displays with some on hover effects. The dice art was done in illustrator and setup for the text to fit within the blank space (die front facing side). The width of the buttons will not change with page size, but they will re-order themselves down to the width of a single button.
The script consists of a number of variables targeting the dice button elements on the page, a number of event listeners which pass dice max values and information about the clicked icon via 'this', and the diceRoll function. I'm going to mostly just talk about the function.
The diceRoll function, at its core, is built from two separate dice roll equations. The first, which is used only on the d100 die (the one that only shows numbers that are multiples of of 10), and the other which runs every other roll. They are both based around Math.random, Math.floor, and multiplying the result by the die amount (then adding 1 to get the correct range). You can check out the formulas in the links above, they're not tricky.
Once it's calculated the correct value for the roll outcome, the function places the value in popup modal, along with the corresponding image (different dice, different shapes) and displays it as a fixed view centered popup. Users can either continue clicking the buttons in the background to roll again, or can click the popup to close it.