I am trying to change the div's background colour using inputs from the radio buttons but I struggle to change colours in reverse order e.g. (pink to black ) or (green to yellow). It works perfectly fine when I try to change colour in order e.g. (black to red) or (red to yellow). I have used console.log to check the variable when I click on a different radio button and it is changing accordingly.
Many thanks
const container = document.querySelector(".container");
const cell = document.querySelector(".cell");
// var rows = 16; //default grid = 16x16
// var cols = 16;
var rows = 16;
var cols = 16;
function makeGrid(rows, cols) {
container.style.setProperty("--rows", rows);
container.style.setProperty("--cols", cols);
for (i = 0; i < (rows * cols); i++) {
let cell = document.createElement("div");
container.appendChild(cell).className = "cell";
container.appendChild(cell).id = i + 1;
};
};
function modifyCell() {
$(document).ready(function() {
var radioValue = $('input[type=radio]:checked').val();
switch (radioValue) {
case 'black':
// console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-black');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-black');
});
break;
case 'red':
console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-red');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-red');
});
break;
case 'pink':
console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-pink');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-pink');
});
break;
case 'yellow':
console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-yellow');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-yellow');
});
break;
case 'green':
console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-green');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-green');
});
break;
case 'blue':
console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-blue');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-blue');
});
break;
case 'violet':
console.log(radioValue);
$(".cell").on("mousedown", function() {
$(this).removeClass('cell').addClass('cell-violet');
})
.on("mouseup", function() {
$(this).removeClass('cell').addClass('cell-violet');
});
break;
default:
alert("!");
};
});
};
function reset() {
$(document).ready(function() {
while (container.firstChild) {
container.firstChild.remove();
};
makeGrid(rows, cols);
modifyCell();
});
};
function resetGrid() {
rows = prompt('Enter a number for grid size. (min = 1, max = 50)');
cols = rows;
$(document).ready(function() {
while (container.firstChild) {
container.firstChild.remove();
};
makeGrid(rows, cols);
modifyCell();
});
};
makeGrid(rows, cols);
modifyCell();
$('input[type=radio]').on('change', function() {
modifyCell();
});
html {
background-image: linear-gradient(45deg, purple, pink);
justify-items: center;
}
header {
margin-bottom: 10px;
padding: 3px;
text-align: center;
font-family: sans-serif;
font-size: 30px;
color: purple;
border: 5px thin purple;
border-radius: 10px;
width: 93vw;
background-color: white;
}
.container {
background-color: white;
display: grid;
margin: 2px;
border: 3px solid purple;
border-radius: 10px;
padding: 6px;
justify-content: center;
width: 90vw;
height: 90vw;
grid-template-rows: repeat(var(--rows), 1fr);
grid-template-columns: repeat(var(--cols), 1fr);
grid-gap: 1px;
}
.container .cell {
background-color: gray;
opacity: 0.3;
}
.container .cell:hover {
background-color: hsl(30, 0%, 95%);
opacity: 1;
}
.container .cell-black {
background-color: black;
opacity: 1;
}
.container .cell-red {
background-color: red;
opacity: 1;
}
.container .cell-pink {
background-color: pink;
opacity: 1;
}
.container .cell-yellow {
background-color: yellow;
opacity: 1;
}
.container .cell-green {
background-color: green;
opacity: 1;
}
.container .cell-blue {
background-color: blue;
opacity: 1;
}
.container .cell-violet {
background-color: violet;
opacity: 1;
}
.button {
border: 2px solid black;
border-radius: 20px;
font-size: 15px;
}
.button:hover {
border: 2px solid black;
border-radius: 20px;
font-size: 15px;
background-color: pink;
}
.radio {
border: 2px solid black;
border-radius: 10px;
box-sizing: border-box;
background-color: white;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-Sketch</title>
</head>
<header>
Etch-a-Sketch
</header>
<body>
<input class="button" type="button" value="Reset Grid" onclick="resetGrid()">
<input class="button" type="button" value="Clear" onclick="reset()">
<div class="container">
</div>
<div class="radio">
<input type="radio" id="black" name="colour" value="black" checked>
<label for="black">Black</label>
<input type="radio" id="red" name="colour" value="red">
<label for="red">Red</label>
<input type="radio" id="pink" name="colour" value="pink">
<label for="pink">Pink</label>
<input type="radio" id="yellow" name="colour" value="yellow">
<label for="yellow">Yellow</label>
<input type="radio" id="green" name="colour" value="green">
<label for="green">Green</label>
<input type="radio" id="blue" name="colour" value="blue">
<label for="blue">Blue</label>
<input type="radio" id="violet" name="colour" value="violet">
<label for="violet">Violet</label>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
You need to remove all the other cell-<color> classes when adding the new color, not just the cell class.
You shouldn't add new event handlers every time the user selects a different radio button. Just have the event handler get the color from the selected radio button.
And instead of using switch/case, you can concatenate the button value to cell- to get the new class to add.
I'm not sure why you had both mousedown and mouseup handlers, since they both did the same thing. So I combined them into a single click handler.
const container = document.querySelector(".container");
const cell = document.querySelector(".cell");
// var rows = 16; //default grid = 16x16
// var cols = 16;
var rows = 16;
var cols = 16;
function makeGrid(rows, cols) {
container.style.setProperty("--rows", rows);
container.style.setProperty("--cols", cols);
for (i = 0; i < (rows * cols); i++) {
let cell = document.createElement("div");
container.appendChild(cell).className = "cell";
container.appendChild(cell).id = i + 1;
};
};
function modifyCell() {
$(document).ready(function() {
$(".cell").on("click", function() {
var radioValue = $('input[type=radio]:checked').val();
$(this).removeClass("cell cell-black cell-red cell-pink cell-yellow cell-green cell-blue cell-violet").addClass("cell-" + radioValue);
});
});
}
function reset() {
$(document).ready(function() {
while (container.firstChild) {
container.firstChild.remove();
};
makeGrid(rows, cols);
modifyCell();
});
};
function resetGrid() {
rows = prompt('Enter a number for grid size. (min = 1, max = 50)');
cols = rows;
$(document).ready(function() {
while (container.firstChild) {
container.firstChild.remove();
};
makeGrid(rows, cols);
modifyCell();
});
};
makeGrid(rows, cols);
modifyCell();
html {
background-image: linear-gradient(45deg, purple, pink);
justify-items: center;
}
header {
margin-bottom: 10px;
padding: 3px;
text-align: center;
font-family: sans-serif;
font-size: 30px;
color: purple;
border: 5px thin purple;
border-radius: 10px;
width: 93vw;
background-color: white;
}
.container {
background-color: white;
display: grid;
margin: 2px;
border: 3px solid purple;
border-radius: 10px;
padding: 6px;
justify-content: center;
width: 90vw;
height: 90vw;
grid-template-rows: repeat(var(--rows), 1fr);
grid-template-columns: repeat(var(--cols), 1fr);
grid-gap: 1px;
}
.container .cell {
background-color: gray;
opacity: 0.3;
}
.container .cell:hover {
background-color: hsl(30, 0%, 95%);
opacity: 1;
}
.container .cell-black {
background-color: black;
opacity: 1;
}
.container .cell-red {
background-color: red;
opacity: 1;
}
.container .cell-pink {
background-color: pink;
opacity: 1;
}
.container .cell-yellow {
background-color: yellow;
opacity: 1;
}
.container .cell-green {
background-color: green;
opacity: 1;
}
.container .cell-blue {
background-color: blue;
opacity: 1;
}
.container .cell-violet {
background-color: violet;
opacity: 1;
}
.button {
border: 2px solid black;
border-radius: 20px;
font-size: 15px;
}
.button:hover {
border: 2px solid black;
border-radius: 20px;
font-size: 15px;
background-color: pink;
}
.radio {
border: 2px solid black;
border-radius: 10px;
box-sizing: border-box;
background-color: white;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<title>Etch-a-Sketch</title>
</head>
<header>
Etch-a-Sketch
</header>
<body>
<input class="button" type="button" value="Reset Grid" onclick="resetGrid()">
<input class="button" type="button" value="Clear" onclick="reset()">
<div class="container">
</div>
<div class="radio">
<input type="radio" id="black" name="colour" value="black" checked>
<label for="black">Black</label>
<input type="radio" id="red" name="colour" value="red">
<label for="red">Red</label>
<input type="radio" id="pink" name="colour" value="pink">
<label for="pink">Pink</label>
<input type="radio" id="yellow" name="colour" value="yellow">
<label for="yellow">Yellow</label>
<input type="radio" id="green" name="colour" value="green">
<label for="green">Green</label>
<input type="radio" id="blue" name="colour" value="blue">
<label for="blue">Blue</label>
<input type="radio" id="violet" name="colour" value="violet">
<label for="violet">Violet</label>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
Related
I want to prevent completely users to modify the values of the number input form in any way that is not using the arrows in the form. Basically I have this:
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");
const footerEl = document.getElementById("footer");
const lowerLetters = "abcdefghijklmnopqrstuvwxyz"
const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "1234567890"
const specialCharacters = "|##~€!$%&/()=?¿"
function randomUpper() {
return upperLetters[Math.floor(Math.random()*upperLetters.length)];
}
function randomNumbers() {
return numbers[Math.floor(Math.random()*numbers.length)];
}
function randomSpecial() {
return specialCharacters[Math.floor(Math.random()*specialCharacters.length)];
}
function randomLower() {
return lowerLetters[Math.floor(Math.random()*lowerLetters.length)];
}
function generateChunk() {
const xs = [];
xs.push(randomLower());
if (upperEl.checked) {
xs.push(randomUpper());
}
if (numberEl.checked) {
xs.push(randomNumbers());
}
if (symbolEl.checked) {
xs.push(randomSpecial());
}
return xs[Math.floor(Math.random()*xs.length)];
}
function generatePassword() {
const len = lenEl.value;
let password = "";
for (let i = 0; i < len; i++) {
password += generateChunk();
}
pwEl.innerText = password;
}
function copy() {
var textArea = document.createElement("textarea");
textArea.value = pwEl.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
//adding class to transition
footerEl.innerText = "Succesfully copied to clipboard!";
footerEl.classList.add("footer-active");
setTimeout(() => {
footerEl.classList.remove("footer-active");
}, 1000)
setTimeout(() => {
footerEl.innerText = "";
}, 1200);
}
generateEl.addEventListener("click", generatePassword);
copyEl.addEventListener("click", copy);
#import url('https://fonts.googleapis.com/css2?family=Raleway:wght#500&display=swap');
* {
box-sizing: border-box;
}
body{
background-color:#37505c;
color: #FFEAD0;
font-family: 'Raleway', sans-serif;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.pw-container{
background-color: #113537;
width:500px;
box-shadow: 5px 10px 8px rgba(0,0,0,0.2);
z-index:2;
}
.pw {
background-color:#37505c;
height: 70px;
width:100%;
position: relative;
align-items: center;
font-size: 2rem;
padding: 1rem;
text-align: center;
}
.pw button{
font-family: inherit;
position: absolute;
top: 0;
right: 0;
transform: translate(0, -20%);
background-color: #FFFFFF;
border: none;
color: #000000;
padding: 0.25rem;
opacity:0;
transition: opacity 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
.pw:hover button {
opacity: 1;
transform: translate(0, -90%)
}
.pw-header {
padding: 1rem;
}
.pw-body {
padding: 0 1rem 1rem;
}
.form-control {
display:flex;
justify-content: space-between;
margin: 0.5rem;
}
.generate {
background-color: #FFFFFF;
display:block;
border: none;
font-size: 1rem;
padding : 0.5rem;
width: 100%;
margin-top: 2rem;
}
.footer {
position: absolute;
top: 1;
bottom: 0;
font-size: 2rem;
width:100%;
background-color:#113537;
text-align: center;
padding: 2rem;
opacity:0;
transition: opacity 0.2s ease;
z-index: 1;
}
.footer-active {
opacity: 1;
transform: translate(0, 0%);
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="pw-container">
<div class="pw-header">
<div class="pw">
<span id="pw">1234</span>
<button id="copy">Copy to clipboard</button>
</div>
</div>
<div class="pw-body">
<div class="form-control">
<label for="len">Length</label>
<input id="len" onKeyDown="return false" type="number" min="5" max="20" value="7">
</div>
<div class="form-control">
<label for="upper">Uppercase</label>
<input id="upper" type="checkbox">
</div>
<div class="form-control">
<label for="number">Numbers</label>
<input id="number" type="checkbox">
</div>
<div class="form-control">
<label for="symbol">Symbols</label>
<input id="symbol" type="checkbox">
</div>
<button class="generate" id="generate">
Generate Password
</button>
</div>
</div>
<div id="footer" class="footer">
</div>
</body>
</html>
Note that in the input, I added onKeyDown="return false", an answer in other post like this one.
However, this is not going to prevent the user from doing a paste of any value he wants, nor moving a value with the mouse into the field. Is there any way to prevent it?
You can easily block any events you want with event handlers like this - it takes a list of events and adds an event handler for each to block it. You can add as many or few events as you need - see a list of Events here:
"keypress paste dragstart drop cut".split(" ").forEach(function(e){
lenEl.addEventListener(e, function(e){
e.preventDefault();
return false;
});
});
Working Example - Accessible Version: Allows tab and arrow keys
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");
const footerEl = document.getElementById("footer");
const lowerLetters = "abcdefghijklmnopqrstuvwxyz"
const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "1234567890"
const specialCharacters = "|##~€!$%&/()=?¿"
"keypress paste dragstart drop cut".split(" ").forEach(function(e){
lenEl.addEventListener(e, function(e){
e.preventDefault();
return false;
});
});
function randomUpper() {
return upperLetters[Math.floor(Math.random()*upperLetters.length)];
}
function randomNumbers() {
return numbers[Math.floor(Math.random()*numbers.length)];
}
function randomSpecial() {
return specialCharacters[Math.floor(Math.random()*specialCharacters.length)];
}
function randomLower() {
return lowerLetters[Math.floor(Math.random()*lowerLetters.length)];
}
function generateChunk() {
const xs = [];
xs.push(randomLower());
if (upperEl.checked) {
xs.push(randomUpper());
}
if (numberEl.checked) {
xs.push(randomNumbers());
}
if (symbolEl.checked) {
xs.push(randomSpecial());
}
return xs[Math.floor(Math.random()*xs.length)];
}
function generatePassword() {
const len = lenEl.value;
let password = "";
for (let i = 0; i < len; i++) {
password += generateChunk();
}
pwEl.innerText = password;
}
function copy() {
var textArea = document.createElement("textarea");
textArea.value = pwEl.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
//adding class to transition
footerEl.innerText = "Succesfully copied to clipboard!";
footerEl.classList.add("footer-active");
setTimeout(() => {
footerEl.classList.remove("footer-active");
}, 1000)
setTimeout(() => {
footerEl.innerText = "";
}, 1200);
}
generateEl.addEventListener("click", generatePassword);
copyEl.addEventListener("click", copy);
#import url('https://fonts.googleapis.com/css2?family=Raleway:wght#500&display=swap');
* {
box-sizing: border-box;
}
body{
background-color:#37505c;
color: #FFEAD0;
font-family: 'Raleway', sans-serif;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.pw-container{
background-color: #113537;
width:500px;
box-shadow: 5px 10px 8px rgba(0,0,0,0.2);
z-index:2;
}
.pw {
background-color:#37505c;
height: 70px;
width:100%;
position: relative;
align-items: center;
font-size: 2rem;
padding: 1rem;
text-align: center;
}
.pw button{
font-family: inherit;
position: absolute;
top: 0;
right: 0;
transform: translate(0, -20%);
background-color: #FFFFFF;
border: none;
color: #000000;
padding: 0.25rem;
opacity:0;
transition: opacity 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
.pw:hover button {
opacity: 1;
transform: translate(0, -90%)
}
.pw-header {
padding: 1rem;
}
.pw-body {
padding: 0 1rem 1rem;
}
.form-control {
display:flex;
justify-content: space-between;
margin: 0.5rem;
}
.generate {
background-color: #FFFFFF;
display:block;
border: none;
font-size: 1rem;
padding : 0.5rem;
width: 100%;
margin-top: 2rem;
}
.footer {
position: absolute;
top: 1;
bottom: 0;
font-size: 2rem;
width:100%;
background-color:#113537;
text-align: center;
padding: 2rem;
opacity:0;
transition: opacity 0.2s ease;
z-index: 1;
}
.footer-active {
opacity: 1;
transform: translate(0, 0%);
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="pw-container">
<div class="pw-header">
<div class="pw">
<span id="pw">1234</span>
<button id="copy">Copy to clipboard</button>
</div>
</div>
<div class="pw-body">
<div class="form-control">
<label for="len">Length</label>
<input id="len" type="number" min="5" max="20" value="7">
</div>
<div class="form-control">
<label for="upper">Uppercase</label>
<input id="upper" type="checkbox">
</div>
<div class="form-control">
<label for="number">Numbers</label>
<input id="number" type="checkbox">
</div>
<div class="form-control">
<label for="symbol">Symbols</label>
<input id="symbol" type="checkbox">
</div>
<button class="generate" id="generate">
Generate Password
</button>
</div>
</div>
<div id="footer" class="footer">
</div>
</body>
</html>
Blocking ALL Key Presses
Note that it is not recommended to prevent all keyDown/keyUp events, for accesibility reasons - it makes your form impossible to use without mouse/touch screen - not only are you unable to change the values, you get stuck inside that input forever and can't even tab out of it! \
Therefore I use keypress instead of keydown above, as keypress allows for control keys to work but if you really need to, you can use keydown instead.
Working Example Blocking ALL Key Presses (inaccessible for visually impaired users)
const pwEl = document.getElementById("pw");
const copyEl = document.getElementById("copy");
const lenEl = document.getElementById("len");
const upperEl = document.getElementById("upper");
const numberEl = document.getElementById("number");
const symbolEl = document.getElementById("symbol");
const generateEl = document.getElementById("generate");
const footerEl = document.getElementById("footer");
const lowerLetters = "abcdefghijklmnopqrstuvwxyz"
const upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const numbers = "1234567890"
const specialCharacters = "|##~€!$%&/()=?¿"
"keydown paste dragstart drop cut".split(" ").forEach(function(e){
lenEl.addEventListener(e, function(e){
e.preventDefault();
return false;
});
});
function randomUpper() {
return upperLetters[Math.floor(Math.random()*upperLetters.length)];
}
function randomNumbers() {
return numbers[Math.floor(Math.random()*numbers.length)];
}
function randomSpecial() {
return specialCharacters[Math.floor(Math.random()*specialCharacters.length)];
}
function randomLower() {
return lowerLetters[Math.floor(Math.random()*lowerLetters.length)];
}
function generateChunk() {
const xs = [];
xs.push(randomLower());
if (upperEl.checked) {
xs.push(randomUpper());
}
if (numberEl.checked) {
xs.push(randomNumbers());
}
if (symbolEl.checked) {
xs.push(randomSpecial());
}
return xs[Math.floor(Math.random()*xs.length)];
}
function generatePassword() {
const len = lenEl.value;
let password = "";
for (let i = 0; i < len; i++) {
password += generateChunk();
}
pwEl.innerText = password;
}
function copy() {
var textArea = document.createElement("textarea");
textArea.value = pwEl.textContent;
document.body.appendChild(textArea);
textArea.select();
document.execCommand("Copy");
textArea.remove();
//adding class to transition
footerEl.innerText = "Succesfully copied to clipboard!";
footerEl.classList.add("footer-active");
setTimeout(() => {
footerEl.classList.remove("footer-active");
}, 1000)
setTimeout(() => {
footerEl.innerText = "";
}, 1200);
}
generateEl.addEventListener("click", generatePassword);
copyEl.addEventListener("click", copy);
#import url('https://fonts.googleapis.com/css2?family=Raleway:wght#500&display=swap');
* {
box-sizing: border-box;
}
body{
background-color:#37505c;
color: #FFEAD0;
font-family: 'Raleway', sans-serif;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
}
.pw-container{
background-color: #113537;
width:500px;
box-shadow: 5px 10px 8px rgba(0,0,0,0.2);
z-index:2;
}
.pw {
background-color:#37505c;
height: 70px;
width:100%;
position: relative;
align-items: center;
font-size: 2rem;
padding: 1rem;
text-align: center;
}
.pw button{
font-family: inherit;
position: absolute;
top: 0;
right: 0;
transform: translate(0, -20%);
background-color: #FFFFFF;
border: none;
color: #000000;
padding: 0.25rem;
opacity:0;
transition: opacity 0.2s ease, transform 0.2s ease;
cursor: pointer;
}
.pw:hover button {
opacity: 1;
transform: translate(0, -90%)
}
.pw-header {
padding: 1rem;
}
.pw-body {
padding: 0 1rem 1rem;
}
.form-control {
display:flex;
justify-content: space-between;
margin: 0.5rem;
}
.generate {
background-color: #FFFFFF;
display:block;
border: none;
font-size: 1rem;
padding : 0.5rem;
width: 100%;
margin-top: 2rem;
}
.footer {
position: absolute;
top: 1;
bottom: 0;
font-size: 2rem;
width:100%;
background-color:#113537;
text-align: center;
padding: 2rem;
opacity:0;
transition: opacity 0.2s ease;
z-index: 1;
}
.footer-active {
opacity: 1;
transform: translate(0, 0%);
z-index: 1;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Generator</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js" defer></script>
</head>
<body>
<div class="pw-container">
<div class="pw-header">
<div class="pw">
<span id="pw">1234</span>
<button id="copy">Copy to clipboard</button>
</div>
</div>
<div class="pw-body">
<div class="form-control">
<label for="len">Length</label>
<input id="len" type="number" min="5" max="20" value="7">
</div>
<div class="form-control">
<label for="upper">Uppercase</label>
<input id="upper" type="checkbox">
</div>
<div class="form-control">
<label for="number">Numbers</label>
<input id="number" type="checkbox">
</div>
<div class="form-control">
<label for="symbol">Symbols</label>
<input id="symbol" type="checkbox">
</div>
<button class="generate" id="generate">
Generate Password
</button>
</div>
</div>
<div id="footer" class="footer">
</div>
</body>
</html>
Note, you no longer need the onkeydown or other event handlers on the input itself in either of these examples
By using event listeners, if the user focuses on the input then blur:
jQuery:
$("input").on("focus", function() {
$(this).blur();
});
Vanilla:
const input = document.querySelector("input#len");
input.addEventListener("focus", function() {
input.blur();
});
So I taught myself coding a few years ago, and got it just enough to put together a few tools for work. I recently had to migrate my site out of CodePen and onto an actual web server. Now I'm having an issue where part of my javascript is executing properly (a portion that empties all other input fields when a user enters an input field using JQuery), but the button that calculates an answer will not work. I believe the .click is not picking it up. Either way I'm not getting error messages, the button just does nothing when I press it.
When I put the code in a snippet to share with you guys, it works (just like it did in CodePen), but the exact same code on my web host does not work. I'm really at a loss here and any help would be greatly appreciated. I feel like I'm missing some small line of code that's supposed to be included in all web files.
$(document).ready(function() {
//Clear out input fields when not selected
$("#sg").focusin(function() {
$("#density").val("");
});
$("#density").focusin(function() {
$("#sg").val("");
});
$("#pounds").focusin(function() {
$("#grams").val("");
$("#percentage").val("");
});
$("#grams").focusin(function() {
$("#percentage").val("");
$("#pounds").val("");
});
$("#percentage").focusin(function() {
$("#pounds").val("");
$("#grams").val("");
});
$(".input_field").focusin(function() {
$("#density").removeClass('highlight');
$("#sg").removeClass('highlight');
$("#pounds").removeClass('highlight');
$("#grams").removeClass('highlight');
$("#percentage").removeClass('highlight');
});
//Calculate on press of enter
$("#button").keypress(function(e) {
if (e.which == 13) {
alert("this is working");
}
});
$("#button").click(function() {
calculateButton();
});
//Calculate values on button hit
function calculateButton() {
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
function removeCommas(x) {
x = x.replace(",", "");
return x;
}
var results = 0;
//Pulling information from input cells
var densityStr = document.getElementById("density").value;
var sgStr = document.getElementById("sg").value;
var poundsStr = document.getElementById("pounds").value;
var gramsStr = document.getElementById("grams").value;
var percentageStr = document.getElementById("percentage").value;
//remove commas from string and then convert string to number
var densityNum = Number(removeCommas(densityStr));
var sgNum = Number(removeCommas(sgStr));
var poundsNum = Number(removeCommas(poundsStr));
var gramsNum = Number(removeCommas(gramsStr));
var percentageNum = Number(removeCommas(percentageStr));
if (densityStr.length !== 0) {
var sgConversion = densityNum / 8.3454;
$("#sg").val(sgConversion.toFixed(3));
$("#density").addClass('highlight');
} else if (sgStr.length !== 0) {
var densityConversion = sgNum * 8.3454;
$("#density").val(densityConversion.toFixed(3));
$("#sg").addClass('highlight');
}
if (poundsStr.length !== 0) {
$("#pounds").addClass("highlight");
densityNum = document.getElementById("density").value;
var gramsConversion = poundsNum * 119.83;
var percentageConversion = poundsNum / densityNum * 100;
$("#grams").val(gramsConversion.toFixed(0));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (gramsStr.length !== 0) {
$("#grams").addClass("highlight");
densityNum = document.getElementById("density").value;
var poundsConversion = gramsNum / 119.83;
var percentageConversion = poundsConversion / densityNum * 100;
$("#pounds").val(poundsConversion.toFixed(2));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (percentageStr.length !== 0) {
$("#percentage").addClass("highlight");
densityNum = document.getElementById("density").value;
var percentageDec = percentageNum / 100;
var poundsConversion = densityNum * percentageDec;
var gramsConversion = poundsConversion * 119.83;
$("#pounds").val(poundsConversion.toFixed(2));
$("#grams").val(gramsConversion.toFixed(2));
}
}
});
body {
margin: 0;
font-family: 'Lato', sans-serif;
background: #d2d2d2;
}
p {
text-align: center;
}
conatiner {
max-width: 1024px;
margin: 0 auto;
}
#navbarContainer {
background: #F44336;
overflow: hidden;
width: 100%;
margin: 0;
}
.navbar {
float: left;
display: block;
font-family: 'Lato', sans-serif;
height: 40px;
width: 200px;
line-height: 40px;
text-align: center;
background: #F44336;
text-decoration: none;
color: #212121;
}
.navbar:hover {
background: #E57373;
color: white;
}
.active {
background: #C62828;
color: white;
}
#formContainer {
width: 450px;
background: #FDFFFC;
margin: 50px auto;
padding: 0px;
border-radius: 8px;
overflow: hidden;
}
#formContainer header {
width: 100%;
height: 130px;
background-color: #3cba54;
overflow: auto;
color: white;
}
header h1 {
margin: 35px 0 0 0;
text-align: center;
line-height: 30px;
}
header h3 {
line-height: 40px;
text-align: center;
margin: 0;
}
#heading {
background-color: #3cba54;
height: 40px;
color: white;
margin-bottom: 25px;
margin-left: -30px;
}
#heading h3 {
line-height: 40px;
}
form {
padding: 20px 0 0 20px;
text-align: center;
}
label {
display: inline-block;
width: 220px;
text-align: right;
}
#myForm .input_field {
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
padding-left: 10px;
width: 125px;
height: 35px;
font-size: 17px;
border-radius: 3px;
background-color: #E0E0E0;
border: none;
}
#button {
display: block;
border-radius: 6px;
width: 200px;
height: 50px;
padding: 8px 15px 8px 15px;
margin: 0 auto;
margin-bottom: 50px;
font-size: 16px;
box-shadow: 0 6px #540000;
background-color: #FF3636;
border: none;
outline: none;
}
#button:active {
background-color: #B81B1B;
box-shadow: 0 1px #27496d;
transform: translateY(5px);
}
.highlight {
background: #FFEB3B !important;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
</body>
</html>
Sometimes putting script tags before the elements on the page can cause issues. You can try to put the scripts at the bottom of the body like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
I'm trying to create checks to validate the input of a user, such as whether he filled it out and is it the correct input. I want it to highlight the fields that contain an error.
I already asked and I was told to create a class however I don't know how to do that.
There is also
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//passwords is too short
if (!form['password'].value.length < 4) {
error.push("Password is too short (Minimum 4 characters)");
}
//height is not a number
if (isNaN(Number(form['height'].value))) {
error.push("Height is not a number");
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
The CSS (form.css):
body {
font-family: sans-serif;
font-size: .9em;
}
form {
width: 26em;
}
label {
font-weight: bold;
float: left;
}
input.wide {
padding: .125em;
width: 25.125em;
}
input.medium {
padding: .125em;
width: 12em;
}
input.narrow {
padding: .125em;
width: 8em;
}
#othercolour {
visibility: hidden;
}
The style.css
body {
font-family: sans-serif;
font-size: .9em;
background-color: rgb(166, 183, 183);
color: black;
}
div#body {
width: 30em;
margin: auto;
padding: 1em 2em;
background-image: url(background.png);
background-repeat: repeat-x;
background-color: rgb(224, 230, 230);
}
h1,h2 {
color: rgb(47, 79, 79);
}
h2 {
margin: .25em 0em .25em 0em;
}
a {
text-decoration: none;
color: rgb(132, 156, 156);
color: white;
font-weight: bold;
}
a:hover {
color: yellow;
}
td, th {
vertical-align: top;
text-align: left;
}
img {
border: 0px;
}
p, .clear {
qclear: both;
}
#catalog {
float: left;
width: 50%;
}
#content {
float: right;
width: 46%;
}
#cart {
border: 1px solid #cccccc;
padding: 0em .5em;
}
#cart form {
display: inline;
}
#cart input.text {
width: 2em;
text-align: right;
}
#welcome {
}
#navigation {
}
#navigation span {
color: rgb(131, 155, 155);
}
#navigation ul {
list-style: none;
padding: 0;
margin: 0;
}
#navigation li {
float: left;
background-color: pink;
border-bottom: solid 1px;
}
#navigation li a {
display: block;
width: 8em;
text-decoration: none;
font-weight: bold;
text-align: center;
padding: .25em;
background-color: rgb(97, 124, 124);
}
#navigation li a:hover {
background-color: rgb(47, 79, 79);
}
You can set the input's CSS border-color property to highlight the field.
var input = document.querySelector('input'),
form = document.querySelector('form');
form.addEventListener('submit', function(e){
e.preventDefault();
if(!input.value.trim()){//if value of input is empty
input.style.borderColor = "red";
} else {
input.style.borderColor = "green";
}
});
<form>
<input placeholder="Enter something">
<br/>
<button>Validate</button>
</form>
If you use the HTML5 validation attributes, then all you’ll need is to set up a CSS rule using the :invalid pseudo class:
:invalid { . . . }
To add a class, use JavaScript's classList.add() function.
Example
function check() {
var element = document.getElementById("input");
if (element.value != "") {
document.write("Valid!");
} else {
element.classList.add("invalid");
}
}
.invalid {
background-color: rgba(255,0,0,.7);
color: white;
}
.invalid::placeholder {
color: white;
}
<input type="text" placeholder="Type Something..." id="input">
<button onclick="check();">Check</button>
Questions:
why when change input radio dont work pause?
why when change input radio , run function move() before than 2 seconds?
This is my code :
$(document).ready(function(){
var timer;
var which;
var number = 0;
move();
$("input[type=radio]").on("change",function(){
move();
})
$(".fa-pause").on("click",function(){
$(this).css({color:"skyblue"});
$(".fa-play").css({color:"red"});
clearInterval(timer);
})
$(".fa-play").on("click",function(){
move();
$(this).css({color:"skyblue"});
$(".fa-pause").css({color:"red"});
})
function move() {
which = $("input[type=radio]:checked").attr("class");
timer = setInterval(function(){
number = parseFloat($(".number").text()) + 1;
if (which == "t1") {
$(".number").hide(750,function(){
$(this).show(100).text(number);
})
}
else if (which == "t2") {
$(".number").fadeOut(750,function(){
$(this).fadeIn(100).text(number);
})
}
else {
$(".number").slideUp(750,function(){
$(this).slideDown(100).text(number);
})
}
},2000)
}
})
ul {
text-align: center;
border: 1px solid skyblue;
display: block;
width:500px;
height: 200px;
margin: 0 auto;
}
li {
display: inline-block;
}
h1 {
display: inline;
color: #fff;
text-shadow: 0px 0px 5px #000;
font-size: 50px;
}
div {
width: 100%;
}
.x {
width: 100%;
height: 100px;
margin-bottom: 20px;
}
.fa {
margin: 0 0 10px 10px;
cursor: pointer;
}
.fa-play {
color: skyblue;
}
.fa-pause {
color: red;
}
<ul>
<div>
<div class="x"><h1 class="number">0</h1></div>
<li class="fa fa-pause"></li>
<li class="fa fa-play"></li>
</div>
<li>
<input type="radio" name="style" class="t1" checked>Show/hide
</li>
<li>
<input type="radio" name="style" class="t2">Fadein/Fadeout
</li>
<li>
<input type="radio" name="style" class="t3">SlideUp/SlideDown
</li>
</ul>
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
You do not check if the interval was added before adding another one. Check before adding another one.
function move() {
if(timer) clearInterval(timer);
...
}
For my assignment, I'm asked to create a game that uses JavaScript. Here is the premise of the game:
At the start of the game, there are ten chips. The player needs to distribute the chips between 11 squares. Each square is designated a number from two to 12. Once player has placed all the chips, he will roll two dice several times. The sum of the dice is recorded and a chip is removed from the corresponding square (if any). The number of rolls needed to remove all 10 chips marks the end of the game.
So I just began the assignment, but I am having trouble keeping a working tally of the number of rolls as it is happening. Parts of it are commented out as I was trying different things. Here is my code:
<!DOCTYPE html>
<html>
<head>
<style>
div.dice{
float:left;
width:32px;
background:#F5F5F5;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
</style>
</head>
<body>
<script type "text/javascript">
function rollDice(){
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled " + diceTotal;
}
var count = 0;
function displayTotal() {
count = parseInt(count) + parseInt(1);
var divData = document.getElementById("showCount");
divData.innerHTML = "Number of Rolls: " + count;
};
/**function displayTotal(val) {
var count = document.getElementById('count').value;
var new_count = parseInt(count, 10) + val;
if (new_count < 0) {new_count = 0;}
document.getElementById('count').value = new_count;
return new_count;
} *//
</script>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button id = "roll" onclick="rollDice()">Roll Dice</button>
<div id ="showCount"></div>
<input type = "button" id = "roll" value = "Roll Dice" onclick = rollDice();/>
<h2 id="status" style="clear:left;"></h2>
</body>
</html>
Also, any suggestive information or links I should see to help with making the chips section (that gets subtracted from every time that total comes up on the die) would be extremely helpful. I have no idea how to do that. Also, how do I add one to the chip boxes on click, that's a mystery as well. I guess I could use some suggestions on counts in JS in general.
Thanks in advance for all the help!
UPDATE
I almost completed this dice game, it does everything the OP requested. I left only one minor thing undone:
Originally I had planned to dynamically remove the text that represented an array element as the real array element was actually removed. Other than that minor aesthetic flaw, it functions properly and it's UI ain't bad either.
I just remembered, there is one function I neglected to add was a reset function which is minor as well.
Plunker
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dice</title>
<style>
html,
body {
box-sizing: border-box;
font: 400 16px/1.5'Palatino Linotype';
height: 100vh;
width: 100vw;
overflow: hidden;
}
*,
*:before,
*:after {
box-sizing: inherit;
margin: 0;
padding: 0;
border: 0;
}
body {
background-color: #222;
color: #EFE;
font-variant: small-caps;
overflow: hidden;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.shell {
position: relative;
padding: 1.5em .75em;
margin: 0 auto;
height: 100%;
width: 100%;
}
.content {
postion: absolute;
font-variant: small-caps;
}
header {
width: 100%;
height: 40px;
position: relative;
margin-bottom: 1.5em;
}
h1 {
color: hsla(45, 100%, 60%, 1);
font-weight: 700;
line-height: 1;
letter-spacing: .5px;
font-size: 3rem;
margin: 0 0 2em 0;
}
.die1,
.die2 {
width: 48px;
height: 48px;
background-color: hsla(0, 100%, 50%, .6);
border-radius: 7px;
display: inline-table;
margin: 2em;
padding-left: 4px;
}
.pip div {
width: 8px;
height: 8px;
background-color: hsla(60, 100%, 80%, 1);
border-radius: 60px;
padding: 1px;
text-align: center;
}
.row {
width: 24px;
height: 8px;
}
.blank div {
width: 8px;
height: 8px;
padding: 1px;
text-align: center;
}
#tossed,
#reset {
height: 32px;
width: 64px;
color: hsla(180, 100%, 30%, 1);
border: 1px inset hsla(228, 100%, 50%, 1);
border-radius: 7px;
text-align: center;
font-size: 1.2rem;
font-variant: small-caps;
display: inline-table;
pointer-events: auto;
cursor: pointer;
}
#reset {
display: none;
}
#set {
display: table;
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
border: 1px ridge hsla(48, 100%, 50%, 1);
border-radius: 7px;
padding: 5px;
}
#field {
width: -moz-fit-content;
width: -webkit-fit-content;
width: fit-content;
border: 1px ridge hsla(48, 100%, 50%, 1);
border-radius: 7px;
padding: 5px;
}
.subFieldset {
pointer-events: none;
}
legend {
color: hsla(45, 100%, 60%, 1);
font-size: 1.5rem;
margin: 0 4em 0 0;
pointer-events: none;
}
#set input {
width: 48px;
height: 32px;
background-color: hsla(0, 0%, 80%, 1);
color: hsla(240, 100%, 40%, 1);
font-family: 'Source Code Pro';
font-size: 1rem;
border: 1px inset hsla(192, 100%, 50%, 1);
border-radius: 7px;
margin: 3px;
padding: 3px;
cursor: pointer;
pointer-events: auto;
display: table-cell;
}
label {
margin: 0 10px 0 0;
font-variant: normal;
display: inline-table;
color: hsla(60, 100%, 80%, 1);
pointer-events: none;
}
output {
color: hsla(240, 100%, 50%, 1);
font-family: 'Source Code Pro';
pointer-events: none;
}
#slotDisplay {
display: table-row;
float: left;
clear: both;
margin: 1em auto;
background-color: hsla(0, 0%, 20%, 1);
border: 1px inset hsla(45, 100%, 60%, 1);
border-radius: 7px;
color: hsla(48, 100%, 50%, 1);
width: 100%;
max-width: 760px;
min-width: 320px;
line-height: 1;
padding: 5px;
font-size: 1.5rem;
pointer-events: none;
}
</style>
</head>
<body>
<header>
<h1>Dice</h1>
</header>
<section class="shell">
<main class="content">
<section class="box">
<fieldset id="field">
<input id="reset" type="reset" value="Reset">
<label for="scored thrown">Score:
<output id="scored" name="scored" for="ui" form="ui">00</output>
/ Rolls:
<output id="thrown" name="thrown" for="ui" form="ui">00</output>
</label>
<button id="tossed" enabled="false">Roll</button>
</fieldset>
<table class="die1">
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
</table>
<table class="die2">
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
<tr class="row">
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
<td class="blank">
<div></div>
</td>
</tr>
</table>
</section>
<form id="ui">
<fieldset id="set">
<legend>Distribute Chips in any Combination</legend>
<label>Chips Remaining:
<output id="wallet" name="wallet" for="ui" form="ui">10</output>
</label>
<br/>
<section class="subFieldset">
<label>
<input type="button" id="b-2" class="feed" value="02" form="ui">
</label>
<label>
<input type="button" id="b-3" class="feed" value="03" form="ui">
</label>
<label>
<input type="button" id="b-4" class="feed" value="04" form="ui">
</label>
<label>
<input type="button" id="b-5" class="feed" value="05" form="ui">
</label>
<label>
<input type="button" id="b-6" class="feed" value="06" form="ui">
</label>
<label>
<input type="button" id="b-7 " class="feed" value="07" form="ui">
</label>
<label>
<input type="button" id="b-8" class="feed" value="08" form="ui">
</label>
<label>
<input type="button" id="b-9" class="feed" value="09" form="ui">
</label>
<label>
<input type="button" id="b-10" class="feed" value="10" form="ui">
</label>
<label>
<input type="button" id="b-11" class="feed" value="11" form="ui">
</label>
<label>
<input type="button" id="b-12" class="feed" value="12" form="ui">
</label>
</section>
<textarea id="slotDisplay" readonly cols="30" rows="1" form="ui"></textarea>
</fieldset>
</form>
</main>
</section>
<script>
/*/////////////][ GLOBAL ][//////////////*/
var slots = [];
var chip = 10;
var roll = 0;
var set = document.getElementById("set");
/*/////////////][ PHASE I ][//////////////*/
set.addEventListener("click", execFeed, false);
function execFeed(event) {
if (event.target !== event.currentTarget) {
var tgt = event.target.id;
console.log('trueTarget: ' + tgt);
var feed = document.getElementById(tgt);
console.log('feed: ' + feed);
var val = feed.value;
console.log('val: ' + val);
var idx = parseInt(splitPop(tgt, '-'), 10) - 2;
console.log('idx: ' + idx);
chip = feedSlot(val, slots);
if (chip === 0) {
set.removeEventListener('click', execFeed, false);
tos.setAttribute('enabled', true);
var str0 = 'Roll the Dice to Match Each Number';
var col0 = 'lime';
msg(str0, col0);
}
}
event.stopPropagation();
}
function feedSlot(val, Arr) {
var wallet = document.getElementById('wallet');
var view = document.getElementById('slotDisplay');
Arr.push(val);
console.log('Arr: ' + Arr);
view.value = Arr;
chip--;
wallet.value = chip;
return chip;
}
var tos = document.getElementById('tossed');
/*/////////////][ PHASE II ][//////////////*/
tos.addEventListener('click', matchRoll, false);
function execRoll() {
var thrown = document.getElementById('thrown');
var scored = document.getElementById('scored');
var die1 = document.querySelector('.die1');
var die2 = document.querySelector('.die2');
var pip1 = selArr('td', die1);
var pip2 = selArr('td', die2);
var rd1 = rollDice(pip1);
var rd2 = rollDice(pip2);
var points = rd1 + rd2;
scored.value = leadZero(points, 2);
roll++;
thrown.value = leadZero(roll, 2);
return points;
}
function matchRoll() {
var val = execRoll();
var tgt = leadZero(val, 2);
console.log('execRoll: ' + tgt);
var arr = slots;
console.log('slots: ' + slots);
var mR = arr.indexOf(tgt);
if (mR === -1) {
var str1 = 'No Match, Roll Again';
var col1 = 'orange';
msg(str1, col1);
} else if (mR > -1 && chip < 9) {
++chip;
var toGo = 10 - chip;
var str2 = tgt + ' Matched, ' + toGo + ' More Matches Left';
var col2 = 'blue';
arr.splice(mR, 1);
msg(str2, col2);
} else {
++chip;
var exit = document.getElementById('reset');
var str3 = 'Completed in ' + roll + ' Rolls';
var col3 = 'yellow';
arr.splice(mR, 1);
msg(str3, col3);
exit.style.display = "block";
tos.style.display = "none";
}
wallet.value = chip;
return false;
}
function rollDice(arr) {
var ran6 = Math.floor(Math.random() * 6) + 1;
blank(arr);
switch (ran6) {
case 1:
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
break;
case 2:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 3:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 4:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 5:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 6:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[3].classList.remove('blank');
arr[3].classList.add('pip');
arr[5].classList.remove('blank');
arr[5].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
}
var pts = ran6;
return pts;
}
/*/////////////][ UTILITIES ][//////////////*/
function msg(str, col) {
var title = document.querySelector('legend');
title.style.color = col;
title.innerHTML = str;
}
function selArr(sel, ele) {
if (!ele) {
ele = document;
}
return Array.prototype.slice.call(ele.querySelectorAll(sel));
}
function blank(arr) {
for (var i = 0; i < arr.length; i++) {
arr[i].classList.remove('pip');
arr[i].classList.add('blank');
}
return false;
}
function leadZero(num, len) {
var str = num.toString();
var zeros = len - str.length;
for (var i = 1; i <= zeros; i++) {
str = "0" + str;
}
return str;
}
function splitPop(str, delim) {
var strX = str.split(delim).pop();
return strX;
}
</script>
</body>
</html>
OLD CONTENT
I made the fun part of this dice game, it's up to you, sir to finish the rest. JS is annotated, good luck.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dice</title>
<style>
html, body { box-sizing: border-box; font: 400 16px/1.5 'Source Code Pro'; height: 100vh; width: 100vw; }
*, *:before, *:after { box-sizing: inherit; margin: 0; padding: 0; border: 0; }
body { background-color: #222; color: #EFE; font-variant: small-caps; overflow: hidden; -webkit-tap-highlight-color: rgba(0,0,0,0); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
.shell { position: relative; padding: 1.5em .75em; margin: 0 auto; height: 100%; width: 100%; }
.content { postion: absolute; font-variant: normal; }
.die1, .die2 { width: 48px; height: 48px; background-color: hsla(0,100%,50%,.6); border-radius: 7px; display: inline-table; margin: 2em; padding-left: 4px; }
.pip div { width: 8px; height: 8px; background-color: hsla(60,100%,80%,1); border-radius: 60px; padding: 1px; text-align: center; }
.row { width: 24px; height: 8px; }
.blank div { width: 8px; height: 8px; padding: 1px; text-align: center; }
#toss { height: 32px; width: 64px; border: 1px inset hsla(0,0%,50%,1); border-radius: 6px; text-align: center; font-size: 1.2rem; font-variant: small-caps; display: inline-table; }
</style>
</head>
<body>
<header>
<h1>Dice</h1>
</header>
<section class="shell">
<main class="content">
<table class="die1">
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
</table>
<button id="toss">Roll</button>
<table class="die2">
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
<tr class="row">
<td class="blank"><div></div></td><td class="blank"><div></div></td><td class="blank"><div></div></td>
</tr>
</table>
</main>
</section>
<script>
// Reference to Dice (2 tables in DOM)
var die1 = document.querySelector('.die1');
var die2 = document.querySelector('.die2');
// Reference to Pips (2 arrays of table-cells in Dice) derived from selArr(sel, ele)☆
var pip1 = selArr('td', die1);
var pip2 = selArr('td', die2);
// Reference to the Toss (1 button triggers the random "roll" of the Dice)
var toss = document.getElementById('toss');
/*
** When the Toss button is clicked, execute function roll(arr)★ twice;
** once for the array of table cells (Pips) in table.die1 (Die One);
** then the other one in table.die2 (Die Two)
*/
toss.addEventListener('click', function(event) {
roll(pip1);
roll(pip2);
return false;
}, false);
/* ★
** Take the array of td (Pips) and add the .blank class to each of them ✪;
** generate a random number 1 thru 6 and determine the layout of the tds (pips)
*/
function roll(arr) {
blank(arr);
var ran6 = Math.floor(Math.random() * 6) + 1;
switch(ran6) {
case 1:
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
break;
case 2:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 3:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 4:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 5:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[4].classList.remove('blank');
arr[4].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
case 6:
arr[0].classList.remove('blank');
arr[0].classList.add('pip');
arr[2].classList.remove('blank');
arr[2].classList.add('pip');
arr[3].classList.remove('blank');
arr[3].classList.add('pip');
arr[5].classList.remove('blank');
arr[5].classList.add('pip');
arr[6].classList.remove('blank');
arr[6].classList.add('pip');
arr[8].classList.remove('blank');
arr[8].classList.add('pip');
break;
}
}
/* ☆
** selArr(sel, ele) (selectorArray) this utility takes a collection of selectors
** and converts them into a real array
*/
function selArr(sel, ele) {
if(!ele) {
ele = document;
}
return Array.prototype.slice.call(ele.querySelectorAll(sel));
}
/* ✪
** blank(arr) takes an array of td (Pips) and adds the .blank class to each one of them
*/
function blank(arr) {
for(var i=0; i < arr.length; i++) {
arr[i].classList.remove('pip');
arr[i].classList.add('blank');
}
return false;
}
</script>
</body>
</html>