Vanilla JavaScript Checkbox Doesn't Work When Checked - javascript

I try to make changes with color saturation of div element every time some checkbox is checked.
allCheckBoxes.forEach(box => {
if(box.checked) {
satura -= 51;
console.log('checked')
}
})
It doesn't work, even can not log into console. According all tutorials everything seems right. I tried successfully almost the same things with checkbox before. So I can not find any mistakes comparing with my own code and any similar questions in Stackoverflow. I use Chrome, but tried in Firefox as well.
I tried to put checkboxes out of tags, doesn't work either.
Please help me to find the solution. Any suggestions will very much appreciated. Thanks in advance.
<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">
<style>
* {
box-sizing: border-box;
}
#schedule td {
width: 70px;
height: 30px;
text-align: center;
border: 1px solid blue;
}
#schedule td:nth-child(2) {
width: 100px;
}
.date {
display: flex;
justify-content: center;
align-items: center;
font-family: Verdana, Geneva, Tahoma, sans-serif;
font-size: 1rem;
padding: 3px;
--color: 255;
background-color: rgb(var(--color), 255, var(--color));
}
.date {
width: 40px;
height: 40px;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="calendar">
<div class="date 19">19</div>
</div>
<div id="today"></div>
<div id="schedule"></div>
<script>
"use strict";
const schedule = document.getElementById('schedule');
let tasks = ['Code', 'Study', 'Tests', 'Sport', 'English'];
let headers = ['Number', 'Task', 'Hours', 'Check'];
let table = '<table>';
let tr = '<tr>';
for (let head of headers) {
tr += `<th>${head}</th>`;
}
tr += '</tr>';
table += tr;
for (let i = 0; i < tasks.length; i++) {
let tr = '<tr>';
tr += `<td>${i+1}</td><td>${tasks[i]}</td><td></td><td></td>`;
tr += '</tr>';
table += tr;
}
table += '</table>'
schedule.innerHTML = table;
document.getElementsByTagName("table")[0].style.borderCollapse = "collapse";
//add checkboxes to last column in a table
let allRows = Array.from(document.getElementsByTagName('tr'));
allRows.forEach(row => {
//remove checkbox from <th>
if (allRows.indexOf(row) === 0) return
let input = document.createElement('input');
input.setAttribute('type', 'checkbox');
row.childNodes[3].appendChild(input);
//add input of hours
let inputHours = document.createElement('input');
inputHours.style.width = '100%';
inputHours.style.height = '100%';
inputHours.style.border = 'none';
inputHours.style.textAlign = 'center';
row.childNodes[2].appendChild(inputHours);
})
//fill calendar in accordance with checked inputs
let dates = document.querySelectorAll('.date');
let today;
setInterval(() => {
const todayDiv = document.getElementById('today');
today = new Date().toUTCString();
todayDiv.innerHTML = today;
}, 1000);
//filter all checkboxes
let allCheckBoxes = [];
let allInputs = document.querySelectorAll('input');
allInputs.forEach(inp => {
if (inp.getAttribute('type') === 'checkbox') {
allCheckBoxes.push(inp);
}
});
console.log(allCheckBoxes)
//bind current date and calendar's day. color saturation
dates.forEach(date => {
let day = today = new Date().getDate();
if (date.classList.contains(day)) {
let satura = 255;
allCheckBoxes.forEach(box => {
if (box.checked) {
satura -= 51;
console.log('checked')
}
})
date.style.setProperty("--color", satura);
}
})
</script>
</body>
</html>

added a button and eventListener. now it works
let colorize = document.querySelector('.colorize')
colorize.addEventListener('click', () => {
dates.forEach(date => {
let day = today = new Date().getDate();
if(date.classList.contains(day)) {
let satura = 255;
allCheckBoxes.forEach(box => {
if(box.checked) {
satura -= 51;
console.log('checked')
}
})
date.style.setProperty("--color", satura);
}
})
})

Related

How can I get the size of the grid to stay the same regardless of the number of divs inside (the new number i enter)?

I am working on The Odin Project and I am on the etch-a-sketch section. I believe I have every part working except resizing the grid when a new number is entered. Any help would be greatly appreciated.
const container = document.getElementById("container");
const button = document.querySelector("input");
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
const total = (numberPerRow * numberPerRow) + numberPerRow;
const box = numberPerRow + 1;
for (i=0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
}
}
hoverColor();
}
makeRows(16);
I have tried to change the inline div style in javascript portion underneath the makeRows function, but nothing seems to work. Unless I completely miss something.
CSS
* {
box-sizing: border-box;
}
#container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
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>Etch-A-Sketch Project</title>
<link rel="stylesheet" href="style.css">
<script src="index.js" defer></script>
</head>
<body>
<input type="button" value="number of squares">
<div id="container">
</div>
</body>
</html>
I'm not familiar with the project exactly, but taking a look at your js, it looks like you're hard-coding the width value for the elements. Something like this may be helpful if you need to use flex:
function makeRows(numberPerRow) {
clearGrid();
const total = numberPerRow * numberPerRow + numberPerRow;
const box = numberPerRow + 1;
for (i = 0; i < total; i++) {
const div = document.createElement("div");
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
//dynamically resize?
div.style.cssText = `border: 1px solid black; height: ${
1000 / numberPerRow
}px; width: ${1000 / numberPerRow}px`;
//dynamically resize?
}
}
hoverColor();
}
Since you are making a grid though, it may be more helpful to use grid layout rather than flex.
https://developer.mozilla.org/en-US/docs/Web/CSS/grid
https://www.w3schools.com/css/css_grid.asp
I'm giving you a solution using display: grid as this is the preferred method to use when creating a grid (it's in the name).
I left the HTML the exact same.
const container = document.getElementById("container");
const button = document.querySelector("input");
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
//Set the grid template columns straight from JavaScript
container.style.gridTemplateColumns = `repeat(${numberPerRow}, 1fr)`;
//Resolved an issue here that was adding an extra row
const total = numberPerRow * numberPerRow;
//Idk what the point of box was so I removed it for the sake of the answer
for (i = 0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
//Moved the gridItem styling to CSS
}
hoverColor();
}
makeRows(16);
* {
box-sizing: border-box;
}
#container {
display: grid;
width: 100%; /* Set whichever width you want here */
aspect-ratio: 1/1;
}
.gridItems {
border: 1px solid black;
}
<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>Etch-A-Sketch Project</title>
<link rel="stylesheet" href="style.css">
<script src="index.js" defer></script>
</head>
<body>
<input type="button" value="number of squares">
<div id="container">
</div>
</body>
</html>
Add this at the top of you js and specify the size of your grid in px. You can add it to makeRows as a variant:
const preservedWidth = 600;
Also add boxWidth to makeRows to calculate the width of your grid element:
const boxWidth = preservedWidth / numberPerRow;
Change this:
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
to:
div.style.cssText = `border: 1px solid black; height: ${boxWidth}; width: ${boxWidth}`;
This is the whole JS code:
const container = document.getElementById("container");
const button = document.querySelector("input");
const preservedWidth = 300;
button.addEventListener('click', ()=> {
numOfSquares();
})
function numOfSquares() {
if (button.value === "number of squares") {
let newNumPerRow = prompt("how many squares per side would you like?", "");
let parse = parseInt(newNumPerRow);
makeRows(parse);
}
}
function hoverColor() {
let items = document.querySelectorAll('.gridItems');
items.forEach(item => {
item.addEventListener('mouseover', () => {
item.style.backgroundColor = 'orange';
});
});
}
function clearGrid() {
const gridArray = Array.from(container.childNodes);
gridArray.forEach(element => {
container.removeChild(element);
})
}
function makeRows (numberPerRow) {
clearGrid();
const total = (numberPerRow * numberPerRow) + numberPerRow;
const box = numberPerRow + 1;
const boxWidth = preservedWidth / numberPerRow;
for (i=0; i < total; i++) {
const div = document.createElement('div');
container.appendChild(div).className = "gridItems";
if (i % box === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = `border: 1px solid black; height: ${boxWidth}; width: ${boxWidth}`;
}
}
hoverColor();
}
makeRows(16);

I would like some help displaying js stuff on the html side of things

I am attempting to display my snake on this dynamic gameboard i made as well as randomly place food
on said board how would i go about turning my js into visual html.
now that i think about it i havent even made a tick function
I've stored the game board and would like to place food randomly within said gameboard
i would assume it would involve toggling a class tied to some styling in css but i do not know how to execute
const gameData = {
getSize(){
let sizeInput = document.querySelector('#sizeInput').value;
sizeInput = parseInt(sizeInput)
console.log(sizeInput)
this.validateBoard(sizeInput)
return sizeInput
},
validateBoard(size){
if(size === NaN || size < 10 || size > 50){
console.log('not good')
return false;
}else if(size === '' || size >= 10 && size <= 50){
console.log('good good')
this.boardSize = size
return true;
}
},
boardSize: 0,
countDownTimer(timer){
if (timer >= 0) {
message.textContent = 'Rendering ' + timer;
timer--
}
return timer;
},
inputMessage(){
let message = document.querySelector('#message')
let validBoard = gameData.validateBoard(gameData.getSize())
console.log(validBoard)
if(validBoard) {
let timer = 5
let countDown = setInterval(function(){
console.log(countDown)
if(timer === 0){
clearInterval(countDown)
generateGameBoard();
}
timer = gameData.countDownTimer(timer)
}, 1000)
} else if(!validBoard){
return message.textContent = 'Invalid entry. Try Again!'
}
},
gameBoard: [],
//currentSnake: [[x,y]],
snakePos: {
x: 4,
y: 4
},
food:[],
//directionFacing: [];
randomfoodSquare(){
let boardSize = this.boardSize
let squareX = Math.floor(Math.random() * (boardSize + 1))
let squareY = Math.floor(Math.random() * (boardSize + 1))
this.food = [squareX, squareY]
}
}
function generateFood(){
randomFoodSquare();
}
let submitSize = document.querySelector('#submit')
function generateGameBoard(){
let sizeInput = gameData.boardSize
let startMenu = document.querySelector('#startMenu')
let table = document.querySelector('#tb')
startMenu.style.display = 'none'
table.style.display = 'flex'
console.log(sizeInput)
for (let i = 0; i < sizeInput; i++) {
console.log(i)
let row = document.createElement('tr');
for(let j = 0; j < sizeInput; j++){
let square = document.createElement('td')
row.appendChild(square)
let x = j
let y = i
gameData.gameBoard.push([x,y])
}
table.appendChild(row)
}
adjustBoardSize();
console.log(gameData.gameBoard)
}
function adjustBoardSize(){
let sizeInput = gameData.boardSize;
let table = document.querySelector('#tb')
let row = document.querySelectorAll('tr')
let square = document.querySelectorAll('td');
let tableWidth = table.offsetWidth;
let tableHeight = table.offsetHeight;
let rowWidth = tableWidth;
row.forEach( rowEl => {
rowEl.style.height = tableHeight/sizeInput + 'px'
})
square.forEach( tdEl=> {
tdEl.style.width = rowWidth/sizeInput + 'px'
})
}
submitSize.addEventListener('click', function(){
gameData.inputMessage();
let sizeInput = document.querySelector('#sizeInput')
sizeInput.value = '';
})
<!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="style.css">
<title>Document</title>
</head>
<body>
<div id="startMenu" class="hidden">
<h1>Beasteds Snake Game</h1>
<h2 id="message">Choose your board size!</h2>
<input id="sizeInput" type="text" placeholder="ex. 20 will give 20*20 grid">
<input id='submit'type="button">
</div>
<table id="tb">
</table>
<script src="snakeGame.js"></script>
</body>
</html>
```
* {
box-sizing: border-box;
}
body{
background-color: cadetblue;
}
#tb{
display: none;
margin: 0 auto;
flex-wrap: wrap;
text-align: center;
border: black solid 1px;
height: 600px;
width: 600px;
}
#startMenu{
display: block;
justify-content: center;
text-align: center;
margin-top: 200px ;
background-color: cyan;
}
td {
background-color: black;
display: flex;
flex-wrap: wrap;
border: rgb(250, 251, 255) solid 1px;
}
tr {
display: flex;
width: 100%;
}
#snakeHead{
color: darkblue;
}

How do I fix my canvas width and height changing every render when I zoom in or out?

I'm developing a sorting visualization website with my friend (https://tann1.github.io/SortingViz/). We both are fairly new to web development. We're currently facing this issue where if you were to zoom in and press play the canvas window shrinks every render or so. Similarly, if you zoom out it'll expand every render or so as well. You can test this bug out through the GitHub link I attached earlier. There's is definitely something that we're missing and we can't seem to identify it. Some help would be very appreciated.
// JS script goes here
let form = document.querySelector('#nBarsInput'); //# = reference to ID
let sortType = document.querySelector('#algoSelect');
let canvas = document.querySelector('.zdog-canvas');
let ctx = canvas.getContext('2d');
let nTextBox = document.getElementById('nTextBox');
let nSubmitButton = document.getElementById('nSubmit');
let replayButton = document.getElementById("replayButton");
let nVal = []; //stores the array that needs to be sorted
let nValUnsorted = [];
let sortSpeed = document.getElementById('sortSpeed');
let unsorted = '#fc90a9'//'#c9751a'
let sorted = '#c94260'
let sorting = '#83BCFF'
//let swapColor = 'red'
nSubmitButton.addEventListener('click', () => { // generate graph when submit button is clicked
generateNums(nTextBox.value);
startSort();
});
function enableInput() {
nSubmitButton.disabled = false;
replayButton.disabled = false;
nTextBox.disabled = false;
sortSpeed.disabled = false;
}
function disableInput() {
nSubmitButton.disabled = true;
replayButton.disabled = true;
nTextBox.disabled = true;
sortSpeed.disabled = true;
}
replayButton.addEventListener('click', () => {
nVal = [...nValUnsorted.map(arr => [...arr])];
//console.log(nValUnsorted);
startSort();
});
async function startSort() {
createCanvas(nTextBox.value);
disableInput();
switch (sortType.value) {
case 'Selection Sort': {
await selectionSort();
break;
}
case 'Insertion Sort': {
await insertionSort();
break;
}
default: {
alert("Invalid sort type");
break;
}
}
enableInput();
}
function generateNums(size) { // generates array of size ntextBox.value, populated with random numbers
nVal = []; // reset array
nValUnsorted = [];
for (let i = 0; i < size; ++i){
let randVal = Math.floor((Math.random() * 0.55 * canvas.height) + (0.40 * canvas.height));
nVal.push([randVal, unsorted]);
nValUnsorted.push([randVal, unsorted]);
}
//copy();
}
// do drawing stuff based on given array and N value
function createCanvas(size) {
let barWidth = (canvas.width/size);
let illo = new Zdog.Illustration({ //main parent object of
element: ".zdog-canvas",
centered: false
});
let rect = new Zdog.Rect({ // create first bar
addTo: illo,
width: barWidth * 0.95,
height: nVal[0][0],
color: nVal[0][1],
fill: true,
stroke: 4,
translate: {y: canvas.height - nVal[0][0] / 2, x : barWidth/2}});
illo.updateRenderGraph();
for(let i = 1; i < size; ++i){ // create rest of the bars by copying the first bar
rect.copy({
height: nVal[i][0],
color: nVal[i][1],
translate: {y: canvas.height - nVal[i][0]/ 2, x : (i * barWidth) + barWidth/2}
});
//nArr.push(rect);
illo.updateRenderGraph();
/* text setup*/
}
for (let i = 0; i < size; ++i) {
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.font = (0.50 * barWidth) + 'px monospace';
ctx.fillText(nVal[i][0], (i * barWidth) + (barWidth/2), 490);
}
}
async function selectionSort() {
let curr_pos = 0; // find the position with the lowest current value
let temp = 0; // need it for the swap
for (let i = 0; i < nTextBox.value - 1; ++i) {
curr_pos = i;
nVal[i][1] = sorting;
await pause(sortSpeed.value);
createCanvas(nTextBox.value);
for (let j = curr_pos + 1; j < nTextBox.value; ++j) { // finds the lowest relative value in the array
if (nVal[j][0] < nVal[curr_pos][0])
curr_pos = j;
}
//swap
temp = nVal[i];
nVal[i] = nVal[curr_pos];
nVal[curr_pos] = temp;
nVal[curr_pos][1] = sorting;
await pause(sortSpeed.value);
createCanvas(nTextBox.value);
nVal[i][1] = sorted;
if (i != curr_pos) {
nVal[curr_pos][1] = unsorted;
}
await pause(sortSpeed.value);
createCanvas(nTextBox.value);
}
nVal[nTextBox.value - 1][1] = sorted;
createCanvas(nTextBox.value);
//console.log(nVal);
return new Promise((resolve, reject) => {resolve('');})
}
async function insertionSort() {
let val, j;
nVal[0][1] = sorted;
for (let i = 1; i < nTextBox.value; i++) {
val = nVal[i]; // current value to sort
val[1] = sorting; //nVal[i][1] = sorting;
await pause(sortSpeed.value);
createCanvas(nTextBox.value);
j = i; // only loop through "sorted" portion
while (j > 0 && val[0] < nVal[j-1][0]) { // keep going through sorted portion until correct position is found
nVal[j] = nVal[j-1]; // shift other values up
nVal[j][1] = sorted;
nVal[j-1] = val;
j--;
await pause(sortSpeed.value);
createCanvas(nTextBox.value);
}
nVal[j][1] = sorted;
await pause(sortSpeed.value);
createCanvas(nTextBox.value);
}
return new Promise((resolve) => {resolve('');})
}
function pause(ms) { // pause execution for a given duration in milliseconds
return new Promise(resolve => {
setTimeout(() => { resolve('') }, ms * 1000);
})
}
/* CSS goes here */
:root {
--pageColor: #FDB;
--buttonColor: #c94260;
--LabelColor: rgba(58, 44, 48, 0.959);
--textColor: #c94260;
--disabledColor: #fc90a9;
}
body {
background-color: var(--pageColor);
font-family: 'Patrick Hand', cursive;
font-size: 25px;
}
h1 {
font-family: 'Source Code Pro', monospace;
font-size: 60px;
color: white;
text-shadow: 2px 5px var(--textColor);
}
#nBarsInput {
display: flex;
flex-direction: column;
align-items: center;
border: 5px solid var(--buttonColor);
border-radius: 15px;
padding: 30px;
width: 1100px;
}
#textInput {
width: 980px;
display: flex;
justify-content: space-between;
}
.button {
background-color: var(--buttonColor);
border-radius: 3px;
border: none;
color: white;
padding: 5px 25px;
margin: 20px 5px;
font-family: 'Inter', sans-serif;
box-shadow: 0 5px #999;
}
.button:hover {
background-color: #83BCFF;
}
.button:active {
background-color: #83BCFF;
box-shadow: none;
transform: translateY(5px);
}
.button:disabled {
background-color: var(--disabledColor);
}
.inputTextBox {
padding: 5px 15px;
border: none;
border-radius: 25px;
}
.inputTextBox:focus {
outline: none;
}
.inputTextBox:disabled
{
}
label {
color: var(---LabelColor);
margin: 5px 15px;
}
main {
display: flex;
flex-direction: column;
align-items: center;
}
.zdog-canvas {
background: var(--pageColor); /*#843b62;*/
flex-basis: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="./style.css">
<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=Caveat:wght#600&family=Patrick+Hand&family=Source+Code+Pro&display=swap" rel="stylesheet">
</head>
<body>
<main>
<h1>SORTING ALGORITHM VISUALIZER</h1>
<div id="nBarsInput">
<div id="textInput">
<div>
<label>Enter a sorting speed (in seconds)</label>
<input type="text" name="sortSpeed" id='sortSpeed' value="0.25" class='inputTextBox'>
</div>
<div>
<label>Enter a Value for N</label>
<input type="text" name="nBars" id='nTextBox' value="5" class='inputTextBox' required>
</div>
</div>
<div id="nBarsButton">
<select id='algoSelect' class='button'>
<option value='Selection Sort'>Selection Sort</option>
<option value='Insertion Sort'>Insertion Sort</option>
</select>
<input type="submit" value="Go" id='nSubmit' class='button'>
<input type="submit" value="Replay" id='replayButton' class='button'>
</div>
</div>
<canvas class='zdog-canvas' width='1000' height='500'></canvas>
</main>
<script src="./script.js" type="module"></script>
<script src="https://unpkg.com/zdog#1/dist/zdog.dist.min.js"></script>
</body>
</html>

How to inject an id attribute to HTML with its value coming from a for loop using JavaScript?

const renderProgress = () => {
let qIndex = 0;
const lastQuestion = 20
const queryAllProgress = document.getElementsByClassName("query__all-progress");
const queryAllProgressId = document.createAttribute("id");
for (qIndex; qIndex <= lastQuestion; qIndex++) {
queryAllProgressId.value += qIndex;
queryAllProgress.setAttributeNode(queryAllProgressId);
}
};
.query__all-progress {
width: 0.9rem;
height: 0.9rem;
margin: 0 0.03rem;
border: 1px solid grey;
display: inline-block;
border-radius: 40%;
}
<div class="query__all-progress"></div>
As you can see, I am trying to get the div element by the class name query__all-progress 'cause I need to give it an attribute of id="". And, the value of the id should be from the for loop, which is the qIndex. I tried to do this but it doesn't work. Please help.
I'm just trying to refactor this code guys. Please help:
const renderProgress = () => {
const lastQuestion = 20;
let qIndex = 0;
const queryProgress = document.getElementById("query__progress");
for (qIndex; qIndex <= lastQuestion; qIndex++) {
queryProgress.innerHTML += `<div class='query__all-progress' id="${qIndex}"></div>`;
}
};
You can try to solve it like this:
In your .html file create a element to serve as a container
<div id="container"></div>
I modified your function a bit like this:
const renderProgress = () => {
// COUNTING VARIABLES
let qIndex = 0;
const lastQuestion = 20
// TO STORE EACH ELEMENT
let querys = '';
// PROCESS
for (qIndex; qIndex <= lastQuestion; qIndex++) {
querys += '<div class="query__all-progress" id="'+ qIndex +'"></div>';
}
// INJECTING GENERATED ELEMENTS TO CONTAINER
document.getElementById('container').insertAdjacentHTML('afterbegin', querys);
}
renderProgress();
.css stays the same
.query__all-progress {
width: 0.9rem;
height: 0.9rem;
margin: 0 0.03rem;
border: 1px solid grey;
display: inline-block;
border-radius: 40%;
}
You should have something like this:
And in the inspector:
I hope it helps you.

Add scores grid game JavaScript

I want to add 10 points when blue box goes into brown box.
I tried to set score = 0 and points to add = 10 but it doesn't work.
I alert '+10 points' and it shows me the alert so I guess the problem is the DOM ?!?
Any suggestions ?
Thanks !
let moveCounter = 0;
let score = 0;
let obs = 10;
document.getElementById('score').textContent = '0';
var grid = document.getElementById("grid-box");
for (var i = 1; i <= 49; i++) {
var square = document.createElement("div");
square.className = 'square';
square.id = 'square' + i;
grid.appendChild(square);
}
var obstacles = [];
while (obstacles.length < 10) {
var randomIndex = parseInt(49 * Math.random());
if (obstacles.indexOf(randomIndex) === -1) {
obstacles.push(randomIndex);
var drawObstacle = document.getElementById('square' + randomIndex);
$(drawObstacle).addClass("ob")
}
}
var playerOne = [];
while (playerOne.length < 1) {
var randomIndex = parseInt(49 * Math.random());
if (playerOne.indexOf(randomIndex) === -1) {
playerOne.push(randomIndex);
var drawPone = document.getElementById('square' + randomIndex);
$(drawPone).addClass("p-0")
}
}
var addPoints = $('#score');
$('#button_right').on('click', function() {
if ($(".p-0").hasClass("ob")) {
alert('add +10 points !!!')
addPoints.text( parseInt(addPoints.text()) + obs );
}
moveCounter += 1;
if ($(".p-0").hasClass("ob")) {
}
$pOne = $('.p-0')
$pOneNext = $pOne.next();
$pOne.removeClass('p-0');
$pOneNext.addClass('p-0');
});
#grid-box {
width: 400px;
height: 400px;
margin: 0 auto;
font-size: 0;
position: relative;
}
#grid-box>div.square {
font-size: 1rem;
vertical-align: top;
display: inline-block;
width: 10%;
height: 10%;
box-sizing: border-box;
border: 1px solid #000;
}
.ob {
background-color: brown;
}
.p-0 {
background-color: blue;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<div id="grid-box">
</div>
<div class="move">
<button id="button_right">right</button><br>
</div>
<div id="score">
</div>
Thank you very much! I am new to JavaScript/ JQuery
Thank you very much!
You are trying to change the HTML inside of the div with id "score".
Selecting the css element using $("#id") retrieves the DOM element and not its contents so adding the score directly to it has no consequences.
What you want to do is: update the score variable and then set the HTML inside the div to the score value.
So instead of just:
addPoints += obs
you should
score += obs
addPoints.html(score)

Categories

Resources