Sitemap
Chamod Dilshan ๐Ÿ˜Ž

Chamod Dilshan ๐Ÿ˜Ž

I'm Chamod Dilshan! ๐Ÿš€ Entrepreneur ๐Ÿš€ ICT undergrad, web dev, and tech enthusiast. Wordsmith on the side. Let's explore tech together

Simple Dice Roller Program in JavaScript

2 min readJun 21, 2024

--

Press enter or click to view image in full size

HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My website</title>

<link rel="stylesheet" href="styles.css">
</head>


<div id="container">

<h1>Dice Roller</h1>

<label ># of Dice</label>

<input type="number" id="numOfDice" value="1" min="1" max="6">

<button onclick="rollDice()">Roll Dice</button>

<div id="diceResult"></div>
<div id="diceImages"></div>



</div>











<script src="script.js"></script>
</body>
</html>

CSS

#container{
font-family: sans-serif;
text-align: center;
font-size: 2rem;
font-weight: bold;
}

button{
font-size: 1.5rem;
padding: 10px 15px;
border-radius: 12px;
border: none;
background-color: hsl(240, 83%, 63%);
color: white;
font-weight: bold;
cursor: pointer;
}

button:hover{
background-color: hsl(240, 77%, 59%);
}


input{
font-size: 2rem;
width: 150px;
text-align: center;
font-weight: bold;
}

#diceResult{
margin: 24px;
}

#diceImages img{
width: 150px;
margin: 5px;
}

Get Chamod Dilshan ๐Ÿ˜Žโ€™s stories inย yourย inbox

Join Medium for free to get updates fromย thisย writer.

JavaScript


function rollDice(){

const numOfDice = document.getElementById("numOfDice").value;
const diceResult = document.getElementById("diceResult");
const diceImages = document.getElementById("diceImages");


const values = [];

const images = [];

for(let i = 0 ; i < numOfDice; i++){
const value = Math.floor(Math.random() *6 ) + 1;
values.push(value);
images.push(`<img src="images/${value}.svg">`)
}

diceResult.textContent = `dice: ${values.join(', ')}`;
diceImages.innerHTML = images.join('');
}

Download the dice images from here . Rename them like the below images . https://game-icons.net/tags/dice.html

Put them in the images folder . Then Try
Source โ€” Bro Code Youtube Channel

--

--

Chamod Dilshan ๐Ÿ˜Ž
Chamod Dilshan ๐Ÿ˜Ž

Written by Chamod Dilshan ๐Ÿ˜Ž

I'm Chamod Dilshan! ๐Ÿš€ Entrepreneur ๐Ÿš€ ICT undergrad, web dev, and tech enthusiast. Wordsmith on the side. Let's explore tech together