Random RGB generator - why am I getting two separate answers? - javascript

I'm attempting to create a game where you have to guess a randomly generated RGB on the screen with it's randomly generated visual counterpart on the screen out of 3 possible selections. For some reason, even though both the RGB value on the screen and the matching color both are assigned to the same variable, 2/10 times I get back a different RGB value for the color, not matching the typed out RGB value. The problem occurs in the 'DOMContentLoaded' event listener.
const easyBtn = document.querySelector('.easy'),
hardBtn = document.querySelector('.hard'),
rgb = document.querySelector('.rgb'),
rand1 = Math.round(Math.random()*300),
rand2 = Math.round(Math.random()*300),
rand3 = Math.round(Math.random()*300),
rand = `rgb(${rand1}, ${rand2}, ${rand3})`,
color1 = document.querySelector('.color1'),
color2 = document.querySelector('.color2'),
color3 = document.querySelector('.color3'),
colorsDiv = document.querySelector('.colors'),
newGame = document.querySelector('.new'),
rand4 = Math.round(Math.random()*301),
rand5 = Math.round(Math.random()*301),
rand6 = Math.round(Math.random()*301),
randd = `rgb(${rand4}, ${rand5}, ${rand6})`,
rand7 = Math.round(Math.random()*302),
rand8 = Math.round(Math.random()*302),
rand9 = Math.round(Math.random()*302),
randdd = `rgb(${rand7}, ${rand8}, ${rand9})`,
// Easy Random Colors
easyRand1 = Math.round(Math.random()*100),
easyRand2 = Math.round(Math.random()*100),
easyRand3 = Math.round(Math.random()*100),
easyRand = `rgb(${easyRand1}, ${easyRand2}, ${easyRand3})`;
easyRand4 = Math.round(Math.random()*101),
easyRand5 = Math.round(Math.random()*101),
easyRand6 = Math.round(Math.random()*101),
easyRandd = `rgb(${easyRand4}, ${easyRand5}, ${easyRand6})`;
easyRand7 = Math.round(Math.random()*102),
easyRand8 = Math.round(Math.random()*102),
easyRand9 = Math.round(Math.random()*103),
easyRanddd = `rgb(${easyRand7}, ${easyRand8}, ${easyRand9})`,
// Hard Random Colors
hardRand1 = Math.round(Math.random()*100),
hardRand2 = Math.round(Math.random()*130),
hardRand3 = Math.round(Math.random()*190),
hardRand = `rgb(${hardRand1}, ${hardRand2}, ${hardRand3})`;
hardRand4 = Math.round(Math.random()*87),
hardRand5 = Math.round(Math.random()*77),
hardRand6 = Math.round(Math.random()*158),
hardRandd = `rgb(${hardRand4}, ${hardRand5}, ${hardRand6})`;
hardRand7 = Math.round(Math.random()*89),
hardRand8 = Math.round(Math.random()*199),
hardRand9 = Math.round(Math.random()*121),
hardRanddd = `rgb(${hardRand7}, ${hardRand8}, ${hardRand9})`,
// Colors styling
colors = document.querySelector('.colors'),
allColors = document.querySelectorAll('.color');
let guessesLeft = 3
easyBtn.addEventListener('click', function() {
easyBtn.style.background = 'rgb(233, 150, 333)';
hardBtn.style.background = 'rgb(233, 230, 333)';
addNewColors();
})
hardBtn.addEventListener('click', function() {
hardBtn.style.background = 'rgb(233, 150, 333)';
easyBtn.style.background = 'rgb(233, 230, 333)';
addHardColors();
})
document.addEventListener('DOMContentLoaded', function() {
rgb.innerHTML = `<h1>${randd}</h1>`;
color1.style.backgroundColor = `${rand}`;
color2.style.backgroundColor = `${randd}`
color3.style.backgroundColor = `${randdd}`
for (var i = colorsDiv.children.length; i >= 0; i--) {
colorsDiv.appendChild(colorsDiv.children[[Math.random() * i | 0]]);
}
})
newGame.addEventListener('click', function() {
window.location.reload();
})
function addHardColors() {
rgb.innerHTML = `<h1>${easyRand}</h1>`;
color1.innerHTML = `<h1 class="color color1" style="background-color: ${easyRand};">`;
color2.innerHTML = `
<h1 class="color color2" style="background-color: ${easyRandd};">`;
color3.innerHTML = `<h1 class="color color3" style="background-color: ${easyRanddd};">`;
}
function addNewColors() {
rgb.innerHTML = `<h1>${hardRandd}</h1>`;
color1.innerHTML = `<h1 class="color color1" style="background-color: ${hardRand};">`;
color2.innerHTML = `
<h1 class="color color2" style="background-color: ${hardRandd};">`;
color3.innerHTML = `<h1 class="color color3" style="background-color: ${hardRanddd};">`;
}
allColors.forEach(function(color) {
color.addEventListener('click', function(e) {
let guess = e.target.style.backgroundColor;
let winningColor = document.querySelector('.rgb').textContent;
console.log(guess)
})
})
* {
box-sizing: border-box;
padding: 0;
margin: 0;
}
body {
font-family: 'Varela Round', sans-serif;
}
.header {
background: rgb(233, 150, 333);
height: 30vh;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
line-height: 7rem;
font-size: 40px;
}
.title {
color: white;
}
.buttons {
background:rgb(233, 230, 333);
height: 5vh;
display: flex;
justify-content: space-between;
}
.difficulty {
display: flex;
position: relative;
right: 190px;
}
.btn {
width: 100px;
background:rgb(233, 230, 333);
border: none;
font-family: 'Varela Round', sans-serif;
}
.colors {
display: flex;
justify-content: space-around;
align-items: center;
background: rgb(233, 230, 200);
height: 65vh;
}
.color {
height: 250px;
border-radius: 15px;
width: 400px;
}
.rgb {
font-size: 20px;
color: white;
}
.new {
position: relative;
left: 30px;
}
#media (max-width: 761px) {
.color {
width: 230px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="rgb.css">
<link href="https://fonts.googleapis.com/css2?family=Varela+Round&display=swap" rel="stylesheet">
<title>Document</title>
</head>
<body>
<header>
<div class="header">
<h1 class="title">RGB Guesser</h1>
<h1 class="rgb"></h1>
</div>
</header>
<section class="buttons">
<button class="btn new">NEW GAME</button>
<div class="difficulty">
<button class="easy btn">EASY</button>
<button class="hard btn">HARD</button>
</div>
</section>
<div class="colors-container">
<section class="colors">
<h1 class="color color1" style="background-color: red;"></h1>
<h1 class="color color2" style="background-color: purple"></h1>
<h1 class="color color3" style="background-color: blue;"></h1>
</section>
</div>
<script src="rgb.js"></script>
</body>
</html>

The maximum value of R, G or B in an RGB colour is 255.
However, in lines such as
rand1 = Math.round(Math.random()*300),
rand2 = Math.round(Math.random()*300),
rand3 = Math.round(Math.random()*300),
rand = `rgb(${rand1}, ${rand2}, ${rand3})`,
you may end up with rand1, rand2 or rand3 having values larger than 255.
Your browser will limit R, G and B values to 255, so if any of rand1 to rand3 are larger than this, then the colour shown by the browser will differ from the colour set in your code.
The fix is straightforward: don't generate colours with the R, G or B values larger than 255.

Related

RGB Color Game if block sometime work and sometime won't work

Hey I am try to create a RGB Color game, here I am facing a Issue that when I refers the tab then inside my randomDiv() function there is a If block(color_fix) which is sometime working and sometime won't working you can check through clicking on refresh tab button inside console, please solve this problem
let first_div = document.getElementById('first_div');
let h4 = document.querySelector('h4');
let h1 = document.createElement('h1');
let color_div = document.querySelector('#color_div');
let createDiv;
h4.style.alignItems = 'center';
h4.append(h1);
let valueRGB = rgb();
h1.innerText = valueRGB.toUpperCase();
h1.style.alignItems = 'center';
first_div.style.backgroundColor = rgb();
function rgb() {
let r = Math.floor(Math.random() * 255 + 0);
let g = Math.floor(Math.random() * 255 + 0);
let b = Math.floor(Math.random() * 255 + 0);
return (`rgb(${r}, ${g}, ${b})`);
}
function threeRandomNumber() {
let threeRandomNumber = Math.floor(Math.random() * 3 + 1);
return threeRandomNumber;
}
function divCreate() {
createDiv = document.createElement('div');
createDiv.classList = 'dynamacily_create_div';
createDiv.style.backgroundColor = `${rgb()}`;
return createDiv;
}
function randomDiv() {
let color_fix = threeRandomNumber();
console.log('outter Background ' + color_fix);
for (let i = 0; i < 3; i++) {
let div_fix = threeRandomNumber();
if (div_fix === 1) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 1) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
} else if (div_fix === 2) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 2) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
} else {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 3) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}
}
}
}
randomDiv()
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
}
body {
display: flex;
justify-content: center;
}
h4,
h5 {
color: #ffffff;
font-size: 40px;
}
#first_div {
width: 900px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
flex-direction: column;
}
#color_div {
height: 400px;
width: 100%;
background-color: black;
display: flex;
flex-direction: row;
justify-content: center;
}
.dynamacily_create_div {
width: 200px;
height: 200px;
border-radius: 25px;
margin: 10px;
border: 1px solid red;
}
<body>
<main>
<div id="first_div">
<h4>THE GREAT</h4>
<h5>GUESSING GAME</h5>
</div>
<div id="second_div">
<button id="newColor">New Color</button>
<button id="playAgain">Play Again</button>
<button id="tryAgain">Try Again</button>
<button id="correct">Correct</button>
<button id="easy">Easy</button>
</div>
<div id="color_div">
</div>
</main>
<script src="app.js"></script>
</body>
Some logical branches are ignored by you.
Both div_fix and color_fix are returned by threeRandomNumber().
div_fix can be any one of [1,2,3].
color_fix can be any one of [1,2,3]. They can be the same or not.
While div_fix===1 and color_fix===2 , code is missing.
While div_fix===1 and color_fix===3 , code is missing.
Please check and fix your problem.
if (div_fix === 1) {
color_div.appendChild(divCreate());
console.log('outter Background inner' + color_fix);
if (color_fix === 1) {
createDiv.style.backgroundColor = valueRGB;
console.log(valueRGB);
console.log('inner Background ' + color_fix);
}else{
// Here!! maybe color_fix === 2 or color_fix === 3, Do sth.
}
}

How to select and manipulate the dynamically created html element with javascript?

I am pretty new to js, and I am building a color scheme generator as a solo project.
I am now stuck on select the html element that created from dynamically.
I tried to select both label and input element below, using document.getElementByClassName but it gives me 'undefined'
I wanna select both label and input elements and add an click eventListner so that they can copy the result color code from that elements.
<label for='${resultColor}' class='copy-label'>Click to copy!</label>
<input class='result-code' id='${resultColor}' type="text" value='${resultColor}'/>`
const colorPickerModes = [ 'monochrome', 'monochrome-dark', 'monochrome-light', 'analogic', 'complement', 'analogic-complement', 'triad quad']
const colorPickerForm = document.getElementById("colorPick-form");
const colorPickerInput = document.getElementById("colorPicker");
const colorPickerModeDropDown = document.getElementById("colorPick-mode");
const resultColorDiv = document.getElementById("result-color-div");
const resultColorCodeDiv = document.getElementById("result-code-div");
let colorPicked = "";
let modePicked = "";
let resultColorDivHtml =''
let resultCodeDivHtml=''
let colorSchemeSetStrings = [];
let resultColorSchemeSet = [];
fetchToRender()
renderDropDownList();
//listen when user change the color input and save that data in global variable
colorPickerInput.addEventListener(
"change",
(event) => {
//to remove # from the color hex code data we got from the user
colorPicked = event.target.value.slice(1, 7);
},
false
);
//listen when user change the scheme mode dropdownlist value and save that data in global variable
colorPickerModeDropDown.addEventListener('change', (event)=>{
modePicked =
colorPickerModeDropDown.options[colorPickerModeDropDown.selectedIndex].text;
})
//whe user click submit btn get data from user's input
colorPickerForm.addEventListener("submit", (event) => {
event.preventDefault();
// To get options in dropdown list
modePicked =
colorPickerModeDropDown.options[colorPickerModeDropDown.selectedIndex].text;
fetchToRender()
});
//when first load, and when user request a new set of color scheme
function fetchToRender(){
if (!colorPicked) {
//initialize the color and mode value if user is not selected anything
colorPicked = colorPickerInput.value.slice(1, 7);
modePicked = colorPickerModes[0]
}
fetch(
`https://www.thecolorapi.com/scheme?hex=${colorPicked}&mode=${modePicked}`
)
.then((res) => res.json())
.then((data) => {
let colorSchemeSetArray = data.colors;
for (let i = 0; i < 5; i++) {
colorSchemeSetStrings.push(colorSchemeSetArray[i]);
}
// to store each object's hex value
for (let i = 0; i < colorSchemeSetStrings.length; i++) {
resultColorSchemeSet.push(colorSchemeSetStrings[i].hex.value);
}
renderColor();
colorSchemeSetStrings = []
resultColorSchemeSet = [];
});
}
function renderColor(){
//to store result of color scheme set object
resultColorDivHtml = resultColorSchemeSet.map((resultColorItem) => {
return `<div class="result-color"
style="background-color: ${resultColorItem};"></div>`;
}).join('')
resultCodeDivHtml = resultColorSchemeSet
.map((resultColor) => {
return `
<label for='${resultColor}' class='copy-label'>
Click to copy!</label>
<input class='result-code' id='${resultColor}'
type="text" value='${resultColor}'/>`;
})
.join("");
resultColorDiv.innerHTML = resultColorDivHtml;
resultColorCodeDiv.innerHTML = resultCodeDivHtml;
}
function renderDropDownList() {
const colorPickerModeOptionsHtml = colorPickerModes
.map((colorPickerMode) => {
return `<option class='colorSchemeOptions' value="#">${colorPickerMode}</option>`;
})
.join("");
colorPickerModeDropDown.innerHTML = colorPickerModeOptionsHtml;
}
* {
box-sizing: border-box;
}
body {
font-size: 1.1rem;
font-family: "Ubuntu", sans-serif;
text-align: center;
margin: 0;
}
/*------Layout------*/
#container {
margin: 0 auto;
width: 80%;
}
#form-div {
width: 100%;
height:10vh;
margin: 0 auto;
}
#colorPick-form {
display: flex;
width: 100%;
height:6vh;
justify-content: space-between;
}
#colorPick-form > * {
margin: 1rem;
height: inherit;
border: 1px lightgray solid;
font-family: "Ubuntu", sans-serif;
}
#colorPick-form > #colorPicker {
width: 14%;
height: inherit;
}
#colorPick-form > #colorPick-mode {
width: 45%;
padding-left: 0.5rem;
}
#colorPick-form > #btn-getNewScheme {
width: 26%;
}
#main {
display: flex;
flex-direction:column;
width:100%;
margin: .8em auto 0;
height: 75vh;
border:lightgray 1px solid;
}
#result-color-div {
width:100%;
height:90%;
display:flex;
}
#result-color-div > *{
width:calc(100%/5);
}
#result-code-div {
width:100%;
height:10%;
display:flex;
}
.copy-label{
width:10%;
display:flex;
padding:0.5em;
font-size:0.8rem;
align-items: center;
cursor: pointer;
background-color: #4CAF50;
color: white;
}
#result-code-div .result-code{
width:calc(90%/5);
text-align: center;
border:none;
cursor: pointer;
}
.result-code:hover, .result-code:focus, .copy-label:hover, .copy-label:focus{
font-weight:700;
}
/*------Button------*/
#btn-getNewScheme {
background-image: linear-gradient(
to right,
#614385 0%,
#516395 51%,
#614385 100%
);
}
#btn-getNewScheme {
padding:0.8rem 1.5rem;
transition: 0.5s;
font-weight: 700;
background-size: 200% auto;
color: white;
box-shadow: 0 0 20px #eee;
border-radius: 5px;
display: block;
cursor: pointer;
}
#btn-getNewScheme:hover,
#btn-getNewScheme:focus {
background-position: right center; /* change the direction of the change here */
color: #fff;
text-decoration: none;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Ubuntu:wght#300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="index.css">
<title>Color Scheme Generator</title>
</head>
<body>
<div id="container">
<div>
<header><h1 class="site-title">🦎 Color Scheme Generator 🦎</h1></header>
</div>
<div id="form-div">
<form id="colorPick-form" method="get" >
<input id="colorPicker" type="color" />
<select name="colorPick-mode" id="colorPick-mode">
</select>
<button type='submit' id="btn-getNewScheme">Get Color Scheme</button>
</form>
</div>
<div id="main">
<div id="result-color-div">
</div>
<div id="result-code-div">
</div>
</div>
<script src="index.js" type="module"></script>
</body>
</html>
I think the problem is rendering timing. So you need to add event listener below the code where set innerHTML.
function renderColor() {
// to store result of color scheme set object
resultColorDivHtml = resultColorSchemeSet
.map((resultColorItem) => {
return `<div class="result-color" style="background-color: ${resultColorItem};"></div>`;
})
.join("");
resultCodeDivHtml = resultColorSchemeSet
.map((resultColor) => {
return `
<label for='${resultColor}' class='copy-label'>Click to copy!</label>
<input class='result-code' id='${resultColor}' type="text" value='${resultColor}'/>
`;
})
.join("");
resultColorDiv.innerHTML = resultColorDivHtml;
resultColorCodeDiv.innerHTML = resultCodeDivHtml;
// here! add event listener
const labels = document.getElementsByClassName("result-code");
Object.entries(labels).forEach(([key, label]) => {
label.addEventListener("click", (event) =>
alert(`copy color: ${event.target.value}`)
);
});
}
const resultColorCodeDiv=document.getElementById("resultColorCodeDiv")
const resultColorDiv=document.getElementById("resultColorDiv")
resultColorSchemeSet=[
{color:"red", code: "#ff0000"},
{color:"green", code: "#00ff00"},
{color:"blue", code: "#0000ff"}]
function renderColor(){
//to store result of color scheme set object
resultColorDivHtml = resultColorSchemeSet.map((resultColorItem) => {
return `<div class="result-color" style="background-color: ${resultColorItem.color};"></div>`
}).join('')
resultCodeDivHtml = resultColorSchemeSet
.map((resultColor) => {
return `
<label for='${resultColor.code}' class='copy-label'>Click to copy!</label>
<input class='result-code' id='${resultColor.code}' type="text" value='${resultColor.code}'/>`
})
.join("")
resultColorDiv.innerHTML = resultColorDivHtml
resultColorCodeDiv.innerHTML = resultCodeDivHtml
addListener(document.querySelectorAll(".result-color"))
addListener(document.querySelectorAll(".result-code"))
}
renderColor()
function addListener(elements){
for(const element of elements){
element.addEventListener("click" , ()=>{
// add copy logic here
console.log("hello")
})
}
}
<body>
<div id="resultColorDiv"></div>
<div id="resultColorCodeDiv"></div>
</body>

my textcontent get erased with each click, how do i keep each clicks value?

I am little confused on the next step. I am building a calculator, so far I can click each button and each button changes the text content to the desired number. However, it's not storing each number, it just replaces it. Which makes sense but I don't know how to make it store the number. By store I mean display like a normal calculator.
I've had some ideas but again not sure how to implement even with the documentation.
ideas:
for each
for loop
I'd really appreciate some guidance on this, please don't re-write my code as this will not help me, i'm still a beginner using vanilla JS. Ideally I would love something with documentation I can read.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital#1&display=swap" rel="stylesheet">
</head>
<body>
<div class="heading">
<h1>Calculator!!!!</h1>
</div>
<div class="value-store">
<span id= "number-input" class="starting-point">0</span>
<span id= "increment" class="increment-point"></span>
</div>
<div id="numbers" class="inputs">
<button id ="seven">7</button>
<button id="eight">8</button>
<button id="nine">9</button>
<button id="multiply">x</button>
<button id="four">4</button>
<button id ="five">5</button>
<button id="six">6</button>
<button id="minus">-</button>
<button id="one">1</button>
<button id="two">2</button>
<button id ="three">3</button>
<button id="add">+</button>
<button id="zero">0</button>
<button id="divide">/</button>
<button id="equals">=</button>
<button id="clear">AC</button>
<button id="del">DEL</button>
</div>
<script src="script.js"></script>
</body>
</html>
css
body {
font-size: medium;
font-family: 'Montserrat', sans-serif;
justify-content: center;
background-color: bisque;
}
h1 {
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
display: flex;
justify-content: center;
padding-top: 100px;
padding-bottom: 100px;
font-family: 'Montserrat', sans-serif;
font-weight: bold;
color:darkgreen;
}
.value-store {
display: flex;
justify-content: center;
border: solid 3px;
padding-top: 20px;
font-family: 'Montserrat', sans-serif;
font-size: x-large;
font-weight: bold;
background-color: black;
color: white;
width: 500px;
}
.starting-point {
display: flex;
justify-items: right;
}
.inputs {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: auto;
justify-content: center;
padding-top: 10px;
border: solid 3px;
width: 500px;
}
button {
font-family: 'Montserrat', sans-serif;
font-weight: bold;
padding: 10px;
border-radius: 50%;
background-color: white;
}
javascript
//display
const numbersValue = document.getElementById("numbers");
const operators = document.getElementById("operator")
//let inputValue_span = document.getElementById("user");
//buttons with numbers
const buttonZero = document.getElementById("zero");
const buttonOne = document.getElementById("one");
const buttonTwo = document.getElementById("two");
const buttonThree = document.getElementById("three");
const buttonFour = document.getElementById("four");
const buttonFive = document.getElementById("five");
const buttonSix = document.getElementById("six");
const buttonSeven = document.getElementById("seven");
const buttonEight = document.getElementById("eight");
const buttonNine = document.getElementById("nine");
//buttons with operators
const plus = document.getElementById("add");
const minus = document.getElementById("minus");
const divide = document.getElementById("divide");
const equals = document.getElementById("equals");
const multiply = document.getElementById("multiply");
//numbers
numbersValue.addEventListener("click", function () {
buttonZero.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 0;}
buttonOne.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 1;}
buttonTwo.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 2;}
buttonThree.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 3;}
buttonFour.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 4;}
buttonFive.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 5;}
buttonSix.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 6;}
buttonSeven.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 7;}
buttonEight.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 8;}
buttonNine.onclick = function changeNumber() {
document.getElementById("number-input").textContent = 9;}
})
//operators
numbers.addEventListener("click", function () {
plus.onclick = function changeNumber() {
document.getElementById("number-input").innerHTML = "+";}
minus.onclick = function changeNumber() {
document.getElementById("number-input").innerHTML = "-";}
divide.onclick = function changeNumber() {
document.getElementById("number-input").innerHTML = "/";}
equals.onclick = function changeNumber() {
document.getElementById("number-input").innerHTML = "=";}
multiply.onclick = function changeNumber() {
document.getElementById("number-input").innerHTML = "x";}
})
//delete all
numbers.addEventListener("click", function () {
clear.onclick = function eraseAll () {
document.getElementById("number-input").innerHTML =0;}
})
//delete one at a time
// show each number pressed
in fact when we click on a button in calculator we don't replace the number
you must do real world act
we multiple last number by 10 and add new number to that
so
when you click 4 -> lastnumber is 0 ->0*10+4 = 4
after that click 4 again -> lastnumber is 4 -> 4*10+4 = 44
and ....
or append by string ability -> 4 append to 4 = 44
you can call a function like this :
buttonFour.onclick = function changeNumber() {
document.getElementById("number-input").textContent = getTextValue(4);}
and this function is :
getTextValue=(data)=>{
return document.getElementById("number-input").textContent*10+data;
}

How to avoid duplicate drag in mxgraph

I want to avoid duplicate drop on mxgraph canvas.
let say I have dragged Pipe on canvas 2nd time it should not allow it be dragged on canvas.
Question: how to avoid duplicate drop on canvas
Here is my working code drag with duplicate allowed
Drag and Drop
var graph = {};
function initCanvas() {
//This function is called onload of body itself and it will make the mxgraph canvas
graph = new mxGraph(document.getElementById('graph-wrapper'));
graph.htmlLabels = true;
graph.cellsEditable = false;
// render as HTML node always. You probably won't want that in real world though
graph.convertValueToString = function(cell) {
return cell.value;
}
const createDropHandler = function (cells, allowSplit) {
return function (graph, evt, target, x, y) {
const select = graph.importCells(cells, x, y, target);
graph.setSelectionCells(select);
};
};
const createDragPreview = function (width, height) {
var elt = document.createElement('div');
elt.style.border = '1px dashed black';
elt.style.width = width + 'px';
elt.style.height = height + 'px';
return elt;
};
const createDragSource = function (elt, dropHandler, preview) {
return mxUtils.makeDraggable(elt, graph, dropHandler, preview, 0, 0, graph.autoscroll, true, true);
};
const createItem = (id) => {
const elt = document.getElementById(id);
const width = elt.clientWidth;
const height = elt.clientHeight;
const cell = new mxCell('', new mxGeometry(0, 0, width, height), 'fillColor=none;strokeColor=none');
cell.vertex = true;
graph.model.setValue(cell, elt);
const cells = [cell];
const bounds = new mxRectangle(0, 0, width, height);
createDragSource(elt, createDropHandler(cells, true, false, bounds), createDragPreview(width, height), cells, bounds);
};
createItem("shape_1");
createItem("shape_2");
createItem("shape_3");
}
#graph-wrapper {
background: #333;
width: 100%;
height: 528px;
}
<html>
<head>
<title>Toolbar example for mxGraph</title>
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<script src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<script src="./app.js"></script>
</head>
<body onload="initCanvas()">
<h4>Drag same box 2 times on the canvas. see duplicate is allowed</h4>
<div>
<div id="shape_1"
style="width: 100px; height: 100px; border-radius: 50%; background: red; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center;">
Pipe
</div>
<div draggable="true" id="shape_2"
style="width: 100px; height: 100px; border-radius: 5%; background: orange; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center;">
Team
</div>
<div draggable="true" id="shape_3"
style="width: 100px; height: 64px; background: #009688; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center; border-radius: 207px; flex-direction: column;">
<div> <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
<path d="M0 0h24v24H0V0z" fill="none" />
<path
d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" />
</svg></div>
<div>Info</div>
</div>
</div>
<div id="graph-wrapper">
</div>
</body>
</html>
You just need check all current cells value of maxgarph in createDropHandler. So get all cells by graph.getModel().cells and then check to see if the cells you want to add exists or not:
let allcells = graph.getModel().cells;
for (var i in allcells)
if (allcells[i].value && (allcells[i].value.id == cells[0].value.id))
return;
var graph = {};
function initCanvas() {
//This function is called onload of body itself and it will make the mxgraph canvas
graph = new mxGraph(document.getElementById('graph-wrapper'));
graph.htmlLabels = true;
graph.cellsEditable = false;
// render as HTML node always. You probably won't want that in real world though
graph.convertValueToString = function (cell) {
return cell.value;
}
const createDropHandler = function (cells, allowSplit) {
return function (graph, evt, target, x, y) {
debugger
let allcells = graph.getModel().cells;
for (var i in allcells)
if (allcells[i].value && (allcells[i].value.id == cells[0].value.id))
return;
const select = graph.importCells(cells, x, y, target);
graph.setSelectionCells(select);
};
};
const createDragPreview = function (width, height) {
var elt = document.createElement('div');
elt.style.border = '1px dashed black';
elt.style.width = width + 'px';
elt.style.height = height + 'px';
return elt;
};
const createDragSource = function (elt, dropHandler, preview) {
return mxUtils.makeDraggable(elt, graph, dropHandler, preview, 0, 0, graph.autoscroll, true, true);
};
const createItem = (id) => {
const elt = document.getElementById(id);
const width = elt.clientWidth;
const height = elt.clientHeight;
const cell = new mxCell('', new mxGeometry(0, 0, width, height), 'fillColor=none;strokeColor=none');
cell.vertex = true;
graph.model.setValue(cell, elt);
const cells = [cell];
const bounds = new mxRectangle(0, 0, width, height);
createDragSource(elt, createDropHandler(cells, true, false, bounds), createDragPreview(width, height), cells, bounds);
};
createItem("shape_1");
createItem("shape_2");
createItem("shape_3");
}
<html>
<head>
<title>Toolbar example for mxGraph</title>
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<script src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<script src="./app.js"></script>
<style>
#graph-wrapper {
background: #333;
width: 100%;
height: 528px;
}
</style>
</head>
<body onload="initCanvas()">
<h4>Drag same box 2 times on the canvas. see duplicate is allowed</h4>
<div>
<div id="shape_1"
style="width: 100px; height: 100px; border-radius: 50%; background: red; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center;">
Pipe
</div>
<div draggable="true" id="shape_2"
style="width: 100px; height: 100px; border-radius: 5%; background: orange; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center;">
Team
</div>
<div draggable="true" id="shape_3"
style="width: 100px; height: 64px; background: #009688; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center; border-radius: 207px; flex-direction: column;">
<div>
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
<path d="M0 0h24v24H0V0z" fill="none" />
<path d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" />
</svg>
</div>
<div>Info</div>
</div>
</div>
<div id="graph-wrapper">
</div>
First of all, I don't have any idea about mxgraph. To solve your problem I made some research on documentation of the library and I didn't find any tips.
I used the basics of the Javascript to achieve this and I didn't touch any of your main code and flow. I just add the draggable_status to graph element on createDropHandler function.
When you drag once, the below code add a status to the object and you can't drag anymore just adding a simple control.
graph.draggable_status = false;
To control, should be in the same function - const createDropHandler = function (cells, allowSplit)
if(graph.draggable_status != false){
const select = graph.importCells(cells, x, y, target);
graph.setSelectionCells(select);
graph.draggable_status = false;
}
The full code snippet is here;
var graph = {};
function initCanvas() {
//This function is called onload of body itself and it will make the mxgraph canvas
graph = new mxGraph(document.getElementById('graph-wrapper'));
graph.htmlLabels = true;
graph.cellsEditable = false;
// render as HTML node always. You probably won't want that in real world though
graph.convertValueToString = function(cell) {
return cell.value;
}
const createDropHandler = function (cells, allowSplit) {
return function (graph, evt, target, x, y) {
if(graph.draggable_status != false){
const select = graph.importCells(cells, x, y, target);
graph.setSelectionCells(select);
graph.draggable_status = false;
}
};
};
const createDragPreview = function (width, height) {
var elt = document.createElement('div');
elt.style.border = '1px dashed black';
elt.style.width = width + 'px';
elt.style.height = height + 'px';
return elt;
};
const createDragSource = function (elt, dropHandler, preview) {
return mxUtils.makeDraggable(elt, graph, dropHandler, preview, 0, 0, graph.autoscroll, true, true);
};
const createItem = (id) => {
const elt = document.getElementById(id);
const width = elt.clientWidth;
const height = elt.clientHeight;
const cell = new mxCell('', new mxGeometry(0, 0, width, height), 'fillColor=none;strokeColor=none');
cell.vertex = true;
graph.model.setValue(cell, elt);
const cells = [cell];
const bounds = new mxRectangle(0, 0, width, height);
createDragSource(elt, createDropHandler(cells, true, false, bounds), createDragPreview(width, height), cells, bounds);
};
createItem("shape_1");
createItem("shape_2");
createItem("shape_3");
}
#graph-wrapper {
background: #333;
width: 100%;
height: 528px;
}
<html>
<head>
<title>Toolbar example for mxGraph</title>
<script type="text/javascript">
mxBasePath = 'https://jgraph.github.io/mxgraph/javascript/src';
</script>
<script src="https://jgraph.github.io/mxgraph/javascript/src/js/mxClient.js"></script>
<script src="./app.js"></script>
</head>
<body onload="initCanvas()">
<h4>Drag same box 2 times on the canvas. see duplicate is allowed</h4>
<div>
<div id="shape_1"
style="width: 100px; height: 100px; border-radius: 50%; background: red; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center;">
Pipe
</div>
<div draggable="true" id="shape_2"
style="width: 100px; height: 100px; border-radius: 5%; background: orange; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center;">
Team
</div>
<div draggable="true" id="shape_3"
style="width: 100px; height: 64px; background: #009688; display: inline-flex; text-align: center; color: #fff; align-items: center; justify-content: center; border-radius: 207px; flex-direction: column;">
<div> <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000">
<path d="M0 0h24v24H0V0z" fill="none" />
<path
d="M11 7h2v2h-2zm0 4h2v6h-2zm1-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" />
</svg></div>
<div>Info</div>
</div>
</div>
<div id="graph-wrapper">
</div>
</body>
</html>

want to show both correct and incorrect answer when the choosen answer is incorrect

Need to get the green background on the correct answer with the red background on the incorrect answer when we choose a wrong answer in the quiz. I need to show a pop-up that congratulate the user to complete this quiz. How is this possible ? I am new to JavaScript . Help me to find solution
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Quick Quiz - Play</title>
<link rel="stylesheet" href="/Main/main.css" />
<link rel="stylesheet" href="game.css" />
</head>
<body>
<div class="container">
<div id="game" class="justify-center flex-column">
<div id="hud">
<div id="hud-item">
<p id="progressText" class="hud-prefix">
Question
</p>
<div id="progressBar">
<div id="progressBarFull"></div>
</div>
</div>
<div id="hud-item">
<p class="hud-prefix">
Score
</p>
<h1 class="hud-main-text" id="score">
0
</h1>
</div>
</div>
<h2 id="question">What is the answer to this questions?</h2>
<div class="choice-container">
<p class="choice-prefix">A</p>
<p class="choice-text" data-number="1">Choice 1</p>
</div>
<div class="choice-container">
<p class="choice-prefix">B</p>
<p class="choice-text" data-number="2">Choice 2</p>
</div>
<div class="choice-container">
<p class="choice-prefix">C</p>
<p class="choice-text" data-number="3">Choice 3</p>
</div>
<div class="choice-container">
<p class="choice-prefix">D</p>
<p class="choice-text" data-number="4">Choice 4</p>
</div>
<div class="timer-quiz">Time left : <span id="timer"></span>
</div>
</div>
<audio id="crctmusic" src="/Assets/win31.mp3" preload="auto"></audio>
<audio id="wrngmusic" src="/Assets/computerError.mp3" preload="auto"></audio>
<script src="game.js"></script>
</body>
</html>
CSS
.choice-container {
display: flex;
margin-bottom: 0.5rem;
width: 100%;
font-size: 6vw;
border: 0.1rem solid rgb(86, 165, 235, 0.25);
background-color: white;
text-align: justify;
}
.choice-container:hover {
cursor: pointer;
box-shadow: 0 0.4rem 1.4rem 0 rgba(86, 185, 235, 0.5);
transform: translateY(-0.1rem);
transition: transform 150ms;
}
.choice-prefix {
padding: 1.5rem 2.5rem;
background-color: #56a5eb;
color: white;
}
.choice-text {
padding: 1.5rem;
width: 100%;
}
.correct {
background-color: #28a745;
}
.incorrect {
background-color: #dc3545;
}
/* HUD */
#hud {
display: flex;
justify-content: space-between;
}
.hud-prefix {
text-align: center;
font-size: 8vw;
}
.hud-main-text {
text-align: center;
}
#progressBar {
width: 15rem;
height: 3rem;
border: 0.3rem solid #56a5eb;
margin-top: 1.5rem;
}
#progressBarFull {
height: 3rem;
background-color: #56a5eb;
width: 0%;
}
/*TIMER*/
.timer-quiz {
color: #efd0ca;
text-align: center;
font-size: 10vw;
background-color: #56a5eb;
width: 100%;
}
Javascript
const question = document.getElementById("question");
const choices = Array.from(document.getElementsByClassName("choice-text"));
const progressText = document.getElementById("progressText");
const scoreText = document.getElementById("score");
const progressBarFull = document.getElementById("progressBarFull");
let currentQuestion = {};
let acceptingAnswers = false;
let score = 0;
let questionCounter = 0;
let availableQuesions = [];
let questions = [{
question: "Inside which HTML element do we put the JavaScript??",
choice1: "<script>",
choice2: "<javascript>",
choice3: "<js>",
choice4: "<scripting>",
answer: 1
},
{
question: "What is the correct syntax for referring to an external script called 'xxx.js'?",
choice1: "<script href='xxx.js'>",
choice2: "<script name='xxx.js'>",
choice3: "<script src='xxx.js'>",
choice4: "<script file='xxx.js'>",
answer: 3
},
{
question: " How do you write 'Hello World' in an alert box?",
choice1: "msgBox('Hello World');",
choice2: "alertBox('Hello World');",
choice3: "msg('Hello World');",
choice4: "alert('Hello World');",
answer: 4
}
];
//CONSTANTS
const CORRECT_BONUS = 1;
const MAX_QUESTIONS = 50;
startGame = () => {
questionCounter = 0;
score = 0;
availableQuesions = [...questions];
getNewQuestion();
};
getNewQuestion = () => {
if (availableQuesions.length === 0 || questionCounter >= MAX_QUESTIONS) {
localStorage.setItem("mostRecentScore", score);
//go to the end page
return window.location.assign("/End/end.html");
}
questionCounter++;
progressText.innerText = `Question ${questionCounter}/${MAX_QUESTIONS}`;
//Update the progress bar
progressBarFull.style.width = `${(questionCounter / MAX_QUESTIONS) * 100}%`;
const questionIndex = Math.floor(Math.random() * availableQuesions.length);
currentQuestion = availableQuesions[questionIndex];
question.innerText = currentQuestion.question;
choices.forEach(choice => {
const number = choice.dataset["number"];
choice.innerText = currentQuestion["choice" + number];
});
availableQuesions.splice(questionIndex, 1);
acceptingAnswers = true;
};
choices.forEach(choice => {
choice.addEventListener("click", e => {
if (!acceptingAnswers) return;
acceptingAnswers = false;
const selectedChoice = e.target;
const selectedAnswer = selectedChoice.dataset["number"];
const classToApply =
selectedAnswer == currentQuestion.answer ? "correct" : "incorrect";
if (classToApply === "correct") {
incrementScore(CORRECT_BONUS);
}
if (classToApply === "correct") {
document.getElementById('crctmusic').play();
} else {
document.getElementById('wrngmusic').play();
}
selectedChoice.parentElement.classList.add(classToApply);
setTimeout(() => {
selectedChoice.parentElement.classList.remove(classToApply);
getNewQuestion();
}, 1000);
});
});
incrementScore = num => {
score += num;
scoreText.innerText = score;
};
startGame();

Categories