I have a counter (up to 5) with Increment and Decrement Buttons the Thing is that When the maximum Limit of 5 is reached and I click the Decrement Button (minus Button) instead of going Down to 4 it goes up to 6 and After that it decrements Properly and this is the Same issue with the Increment Button.
So can anyone tell why this is happening and How to resolve it?
Any help is Highly Appreciated.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 1
function incre() {
if (value <= 5) {
let holder = value++
text.innerText = holder
let updatedEth = 0.25 * holder
addedAmount.innerText = updatedEth
} else {
alert('You can not take More than Five NFTs')
}
}
function decre() {
if (value >= 1) {
let holder = value--
text.innerText = holder
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
} else {
alert('you can not')
}
}
<div>
<button class="decrement" onclick="decre()">-</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">+</button>
</div>
<div>
<p><span class="added-amount"> 0.25 </span> eth</p>
</div>
You need to use the prefix operator to appear the result on click, also make the value as 0 in initialization otherwise the first value will be 2. you could remove the holder variable in this use case.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 0
function incre(){
if(value < 5){
text.innerText = ++value
let updatedEth = 0.25 * value
addedAmount.innerText = updatedEth
}else{
alert('You can not take More than Five NFTs')
}
}
function decre(){
if(value > 0){
text.innerText = --value
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
}else{
alert('you can not')
}
}
<!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>Document</title>
</head>
<body>
<div>
<button class="decrement" onclick="decre()">
-
</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">
+
</button>
</div>
<div>
<p> <span class="added-amount"> 0.25 </span> eth</p>
</div>
</body>
</html>
Instead of pre/post decrementing the value, you can simply do text.innerText = holder-1; and then decrease value by 1.
let increment = document.querySelector('.increment')
let decrement = document.querySelector('.decrement')
let text = document.querySelector('.text')
let addedAmount = document.querySelector('.added-amount')
let value = 1
function incre(){
if(value <= 5){
let holder = value++
text.innerText = holder
let updatedEth = 0.25 * holder
addedAmount.innerText = updatedEth
}else{
alert('You can not take More than Five NFTs')
}
}
function decre(){
if(value >= 1){
let holder = value;
text.innerText = holder-1;
value -= 1;
console.log(addedAmount.innerText - 0.25)
let minusedAmount = addedAmount.innerText - 0.25
addedAmount.innerText = minusedAmount
}else{
alert('you can not')
}
}
<!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>Document</title>
</head>
<body>
<div>
<button class="decrement" onclick="decre()">
-
</button>
<p class="text">0</p>
<button class="Increment" onclick="incre()">
+
</button>
</div>
<div>
<p> <span class="added-amount"> 0.25 </span> eth</p>
</div>
</body>
</html>
Related
Its a simple poll app in Js. where user vote count and percentages will change accordingly. But the problem i am facing is the percentages are not updated, lets say total vote is 5 and yes vote is 3 among them so yes vote percentage should be updates as the no votes comes along but it not been updated automatically.
let count = document.getElementById('count')
let ncount = document.getElementById('ncount')
let num = 0;
let nnum = 0;
document.getElementById('btn').addEventListener('click', () => {
let nper = document.getElementById('per')
num++
let total = num + nnum
let totalPercentages = num / total * 100
count.innerHTML = num + " " + "percentages" + totalPercentages + '%'
nper.innerHTML = nnum + num + '<div></div>' + "total vote cast"
})
document.getElementById('Nbtn').addEventListener('click', () => {
let per = document.getElementById('per')
nnum++
let total = num + nnum
let totalPercentages = nnum / total * 100
ncount.innerHTML = nnum + " " + totalPercentages + '%'
per.innerHTML = num + nnum + '<div></div>' + "total vote cast"
})
<!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>Document</title>
</head>
<body>
<fieldset>
<legend>do you like pizza</legend>
<div id="count"> 0</div>
<button id="btn">yes</button>
<br></br>
<div id="ncount"> 0</div>
<button id="Nbtn">no</button>
<br></br>
<div id="per"></div>
</fieldset>
<script src="main.js"></script>
</body>
</html>
Using the event handlers as defined by the OP, the percentage updates can be handled in a separate function.
There are a few other updates to the code
statements should end with semicolons (;)
variables that are only assigned once should be declared with const
the <br> tag does not have a </br> closing tag
// const should be used for variables which are only assigned a value once
// every statement should end with a semicolon (;)
const count = document.getElementById('count');
const ncount = document.getElementById('ncount');
const per = document.getElementById('per');
let num = 0;
let nnum = 0;
// update the count, ncount and per displays
function updatePer() {
let total = num + nnum;
count.innerHTML = num + " percentages " + (num / total * 100) + '%';
ncount.innerHTML = nnum + " percentages " + (nnum / total * 100) + '%';
per.innerHTML = (nnum + num) + "<br>total vote cast";
}
// count each button click and call the updatePer function
document.getElementById('btn').addEventListener('click', () => {
num++;
updatePer();
})
document.getElementById('Nbtn').addEventListener('click', () => {
nnum++;
updatePer();
})
<!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>Document</title>
</head>
<body>
<fieldset>
<legend>do you like pizza</legend>
<div id="count"> 0</div>
<button id="btn">yes</button>
<br>
<div id="ncount"> 0</div>
<button id="Nbtn">no</button>
<br>
<div id="per"></div>
</fieldset>
<script src="main.js"></script>
</body>
</html>
const poll = document.getElementById("poll");
// counts is an object literal which has two properties - yes and no
// yes and no are objects with an element and a count value
// these are used to keep track of the counts and update the corresponding element
const counts = {
yes: {
el: document.getElementById('yes-count'),
value: 0
},
no: {
el: document.getElementById('no-count'),
value: 0
}
};
const percentage = document.getElementById("percentage");
// get all the clicks in the poll
poll.addEventListener("click", evt => {
// get the id of the button that was clicked
if (evt.target.tagName === "BUTTON") {
const id = evt.target.id;
// remove '-btn' from the id
const count = id.replace('-btn', '');
// make sure the id is a property name
if (typeof counts[count] === "object") {
// get the counts object
const counter = counts[count];
// update the counter
counter.value++;
// update the display
counter.el.textContent = counter.value;
// update the percentage
percentage.textContent = ((counts.yes.value / (counts.yes.value + counts.no.value) * 100.0)).toFixed(2) + '%';
}
}
});
<fieldset id="poll">
<legend>do you like pizza</legend>
<output id="yes-count"> 0</output>
<button id="yes-btn">yes</button>
<br>
<output id="no-count"> 0</output>
<button id="no-btn">no</button>
<br>
<p>Percentage of people that like pizza <output id="percentage"></output></p>
</fieldset>
This piece of javascript successfully generated random number but I'm having challenge in fetching the variable value so I can use it as desired. below is the working code:
let btn = document.querySelector('button');
let output = document.querySelector('#output');
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() * step1;
let result = Math.floor(step2) + min;
return result;
}
function createArrayOfNumbers(start, end){
let myArray = [];
for(let i = start; i <= end; i++) {
myArray.push(i);
}
return myArray;
}
let numbersArray = createArrayOfNumbers(1,10);
btn.addEventListener('click', () => {
if(numbersArray.length == 0){
output.innerText = 'No More Random Numbers';
return;
}
let randomIndex = getRandomNumber(0, numbersArray.length-1);
let randomNumber = numbersArray[randomIndex];
numbersArray.splice(randomIndex, 1)
output.innerText = randomNumber;
});
<!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>Document</title>
</head>
<body>
<button>Generate</button>
<h1 id="output" style="text-align: center">Random Number</h1>
<script src="script.js"></script>
</body>
</html>
There are several ways of doing but the easiest would be to create a global variable outside the function and then when that random number is generated assign that number to that global variable you can write it like this:
var myvariable = 0;
let btn = document.querySelector('button');
let output = document.querySelector('#output');
//all of your code and then at the end
numbersArray.splice(randomIndex, 1)
output.innerText = randomNumber;
myvariable = randomNumber;
});
Now this variable is accessible outside the function. Hope that helps!
I'm working on The Odin Project curriculum at the moment, and the calculator is the final project of the foundations. I have a mostly working app, but I just can't seem to be able to chain multiple operators without having to press the equals button in between. To clarify, I should be able to do 5+5+5 etc. At the moment however, it does nothing after the first 5+5. I have been stuck on this for quite a while, and am getting frustrated.
Any help is greatly appreciated.
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">
<link rel="stylesheet" href="style.css">
<title>Calculator</title>
</head>
<body>
<div class="calculator">
<div class="output">
<div class="previous"></div>
<div class="operator-display"></div>
<div class="current"></div>
</div>
<button class="span-two clear">Clear</button>
<button class="span-two delete">Delete</button>
<button class="number">1</button>
<button class="number">2</button>
<button class="number">3</button>
<button class="operator">+</button>
<button class="number">4</button>
<button class="number">5</button>
<button class="number">6</button>
<button class="operator">-</button>
<button class="number">7</button>
<button class="number">8</button>
<button class="number">9</button>
<button class="operator">*</button>
<button class="decimal">.</button>
<button class="number">0</button>
<button class="equals">=</button>
<button class="operator">/</button>
</div>
</body>
<script src="script.js"></script>
</html>
javascript:
const numberBtns = document.querySelectorAll(".number");
const operationBtns = document.querySelectorAll(".operator");
const equalsBtn = document.querySelector(".equals");
const clearBtn = document.querySelector(".clear");
const deleteBtn = document.querySelector(".delete");
const previous = document.querySelector(".previous");
const current = document.querySelector(".current");
const operatorDisplay = document.querySelector(".operator-display");
let decimalBtn = document.querySelector(".decimal");
let firstNumber = 0;
let secondNumber = 0;
let result;
//function to clear output screen
function clearOutput(){
previous.innerText = "";
current.innerText = "";
operatorDisplay.innerText = "";
}
//calls function to clear screen on a click
clearBtn.addEventListener("click", ()=>{
clearOutput();
})
//add number to screen on click
numberBtns.forEach(button => {
button.addEventListener('click', ()=>{
current.innerText += button.innerText;
})
})
decimalBtn.addEventListener('click', ()=>{
addDecimal();
})
//when pressing an operator button, the current operand is moved to the previous operand //place
operationBtns.forEach(button =>{
button.addEventListener('click', ()=>{
if (operatorDisplay.innerText != "") {
operate();
}
else{
previous.innerText = current.innerText;
firstNumber = previous.innerText;
current.innerText = "";
operatorDisplay.innerText = button.innerText;
}
})
})
//calculates result based on chosen operator
equalsBtn.addEventListener('click', ()=>{
secondNumber = current.innerText;
operate();
//Display error message if user tries to divide by 0
if (secondNumber === "0" && operatorDisplay.innerText === "/") {
errorMessage();
}
//pressing equals button does nothing if either operand is empty
if (current.innerText != "" && previous.innerText != "") {
displayResult();
}
})
//deletes last number of the current operand on click
deleteBtn.addEventListener('click', ()=>{
current.innerText = current.innerText.slice(0, -1);
})
//displays result
function displayResult(){
clearOutput();
//rounds the result in case of a ridiculous number of decimals
current.innerText = Math.round(result * 10000) / 10000;
}
function operate(){
if (operatorDisplay.innerText === "+") {
result = parseFloat(firstNumber) + parseFloat(secondNumber);
}
if (operatorDisplay.innerText === "-") {
result = parseFloat(firstNumber) - parseFloat(secondNumber);
}
if (operatorDisplay.innerText === "*") {
result = parseFloat(firstNumber) * parseFloat(secondNumber);
}
if (operatorDisplay.innerText === "/") {
result = parseFloat(firstNumber) / parseFloat(secondNumber);
}
}
function errorMessage(){
clearOutput();
result = "Division by 0 impossible";
}
//adds decimal point
function addDecimal(){
if (!current.innerText.includes(".")) {
current.innerText += ".";
}
}
I coded a simple game where you have to guess a random number. The user submits the number and the app compares it to the random generated number. The user gets back a message whether their number is bigger or smaller than the solution.
The Code is :
const start = document.getElementById("start")
const description = document.getElementById("description")
const gameBody = document.getElementById("root")
let valaszokHTML
start.addEventListener("click", gameStart)
function gameStart() {
gameBody.innerHTML = '<input type = "number" placeholder ="Enter your guess..." "min="1" max="1000" id="usernumber">' +
'</input>' + '<button id="guessbutton">This is my guess!</button>'
const guessSubmit = document.getElementById("guessbutton")
guessSubmit.addEventListener("click", compareNumbers)
}
function compareNumbers() {
let userNumber = document.getElementById("usernumber").value
if (myNumber.szamom > userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's bigger than " + userNumber
} else if (myNumber.szamom < userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's smaller than " + userNumber
} else if (myNumber.szamom == userNumber) {
gameBody.innerHTML = "<h1>Right! You won!</h1>"
}
}
const myNumber = {
szamom: Math.floor(Math.random() * 1000) + 1,
}
<!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>Document</title>
</head>
<body>
<div id="root">
<div id="description">
<h1> Try to guess the number between 1 and 1000!</h1>
</div>
<button id="start">Game start</button>
</div>
<script src="practice.js"></script>
</body>
</html>
So my problem that I can can only click the guessSubmit button once. The first time I click it creates the HTML I want, but then I can't use the button anymore. I want it to create a new h1 element whenever I click it (so it will be a bunch of h1 elements below/above each other, until the user gets the number)
Can you please help me and explain, what am I doing wrong?
I would be really appreciate to get some responses.
You have to add a addEventListener at the end of your compareNumbers function, because it is not global.
const start = document.getElementById("start")
const description = document.getElementById("description")
const gameBody = document.getElementById("root")
let valaszokHTML
start.addEventListener("click", gameStart)
function gameStart() {
gameBody.innerHTML = '<input type = "number" placeholder ="Enter your guess..." "min="1" max="1000" id="usernumber">' +
'</input>' + '<button id="guessbutton">This is my guess!</button>'
let guessSubmit = document.getElementById("guessbutton");
guessSubmit.addEventListener("click", compareNumbers);
}
function compareNumbers() {
let userNumber = document.getElementById("usernumber").value
if (myNumber.szamom > userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's bigger than " + userNumber
} else if (myNumber.szamom < userNumber) {
gameBody.innerHTML += "<h1>Wrong! It's smaller than " + userNumber
} else if (myNumber.szamom == userNumber) {
gameBody.innerHTML = "<h1>Right! You won!</h1>"
}
let guessSubmit = document.getElementById("guessbutton");
guessSubmit.addEventListener("click", compareNumbers);
}
const myNumber = {
szamom: Math.floor(Math.random() * 1000) + 1,
}
<!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>Document</title>
</head>
<body>
<div id="root">
<div id="description">
<h1> Try to guess the number between 1 and 1000!</h1>
</div>
<button id="start">Game start</button>
</div>
<script src="practice.js"></script>
</body>
</html>
When you do gameBody.innerHTML += "some text" you're completely destroying and recreating all the content, hence eventListener of guessSubmit will be destroyed too. So maybe add some <h1 id="answer_text"></h1> and manipulate it's innerHtml
I am designing a quiz that generates the question & answers dynamically each time, I have written an if-else statement to check if the answer is right but something isn't quite right. The increment score function doesn't work properly as random numbers are added and the alert box pops up more than once. It seems there is a bounce within the function but I can't figure out what it is.
// Game controls
const startButton = document.getElementById('start-button');
const quitButton = document.getElementById('quit-button');
const mainHeading = document.getElementById('main-heading');
const gameContainer = document.getElementById('game-container');
const scoreOutput = document.getElementById('score-total');
var questionCountOutput = document.getElementById('question-count');
let currentScore = 0;
let questionCount = 0;
startButton.addEventListener('click', startGame);
quitButton.addEventListener('click', quitGame);
const maxQuestions = 10;
const scoreValue = 20;
// Start game
function startGame(event) {
startButton.classList.add('hidden')
mainHeading.classList.add('hidden')
gameContainer.classList.remove('hidden')
questionCount = 0;
currentScore = 0;
generateQuestion()
};
// Quit Game
function quitGame(event) {
if (window.confirm('Are you sure you want to quit?')) {
gameContainer.classList.add('hidden')
startButton.classList.remove('hidden')
}
};
// Generates the questions
function generateQuestion() {
// Increment question count by 1 each time
questionCount++;
questionCountOutput.innerText = `${questionCount}`;
// variables to help generate question
let countriesCount = countriesList.length;
let randomNumber = getRandomInt(0, countriesCount);
let chosenCountry = (countriesList[randomNumber].country); // Generate random country from array
let correctAnswer = (countriesList[randomNumber].capital); // Generate the correct capital city from array
// Define correct answer
let isCorrectQuestionAnswer = {
question: chosenCountry,
option: correctAnswer
};
// Generate 3 random cities from capitalListOptions to act as other answer options
let answerOption1 = (countriesList[getRandomInt(0, countriesList.length)].capital);
let answerOption2 = (countriesList[getRandomInt(0, countriesList.length)].capital);
let answerOption3 = (countriesList[getRandomInt(0, countriesList.length)].capital);
// define option outputs to loop through
let optionOutputs = [{
'question': chosenCountry,
'option': correctAnswer
},
{
'question': chosenCountry,
'option': answerOption1
},
{
'question': chosenCountry,
'option': answerOption2
},
{
'question': chosenCountry,
'option': answerOption3
}
];
// Randomise the outputs so the correct answer isn't in the same place all the time
randomOptionOutputs = optionOutputs.sort(() => Math.random() - 0.5);
let buttonOutputs = '';
let i = 0;
// Loop through the options and retrieve their key values
//add key values to as button attributes
Object.keys(randomOptionOutputs).forEach(function(key) {
// Code to define the html for the buttons
buttonOutputs += '<button id="answer-' + i + '" data-answer="' + randomOptionOutputs[key]['option'] + '" data-country="' + randomOptionOutputs[key]['question'] + '" class="answer-btn" >' + randomOptionOutputs[key]['option'] + '</button>';
i++;
});
// Create the answer buttons and the questionText
document.getElementById('country-name').innerHTML = chosenCountry;
document.getElementById('answers-container').innerHTML = buttonOutputs;
// Loop through the buttons that have been created and add event listeners to them
for (let i = 0; i < 4; i++) {
document.getElementById("answer-" + i).addEventListener("click", function() {
checkAnswer(isCorrectQuestionAnswer)
});
};
};
// Generate random number to use as array index to generate questions and answers
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
};
// Checks if the answer selected is right, increments the score if it is, then moves on the to the next question
function checkAnswer(isCorrectQuestionAnswer) {
// Using a jquery method, retrieve the data-answer for the button clicked and compare this with the isCorrectQuestionAnswer object 'option'
$(document).on('click', '.answer-btn', function() {
var clickedButtonAnswer = $(this).data('answer');
// var clickedButtonQuestion = $(this).data('country');
if ((clickedButtonAnswer === isCorrectQuestionAnswer["option"])) {
$(this).addClass("correct");
incrementScore(scoreValue);
alert('Well done!!! You got that right');
generateQuestion();
return
} else {
$(this).addClass("incorrect");
alert("Ahhh that wasn't quite right - no worries, you'll get it next time!");
generateQuestion();
return
};
});
};
// function to increment the score with each new question
function incrementScore(num) {
currentScore += num;
scoreOutput.innerText = `${currentScore}`;
};
<!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="../assets/css/style.css">
<title>Around the World!</title>
</head>
<body>
<div class="navbar-container">
<nav class="navbar-top">
<ul>
<li>
Home
</li>
<li>
Rules
</li>
<li>
Play Game
</li>
<li>
High Scores
</li>
</ul>
</nav>
</div>
<div class="title-container">
<h1 id="main-heading">Let's Play</h1>
</div>
<div id="start-game" class="container">
<button id="start-button" class="btn">Start Game</button>
</div>
<div id="game-container" class="hidden">
<div id="progress-container">
<p class="progress">Question <span id="question-count"></span> of 10</p>
</div>
<div id="score-container">
<p class="progress">Score: <span id="score-total">0</span></p>
</div>
<div id="questions-container" class="container">
<h2 class="question">What is the capital city of <span id="country-name">country name</span>?</h2>
</div>
<div id="answers-container" class="container">
</div>
<div id="quit-game" class="container">
<button id="quit-button" class="btn">Quit Game</button>
</div>
</div>
<script src="../assets/js/script.js" defer></script>
<script src="../assets/js/quiz.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</body>
</html>