Why are my buttons on javascript not responding when clicked? - javascript

Idk whats wrong, I tried adding id to buttons and that didn't work either so I just went back to using the class of the buttons in querySelect. I also tried using onclick and still no response. The button is supposed to turn green or red when clicked depending on whether it is correct. There are also no errors in developer tools.
< script >
function Q1correct() {
correct.style.backgroundColor = 'green';
document.querySelector('#resultQ1').innerHTML = 'Correct!';
}
function Q1wrong() {
for (let i = 0; i < incorrects.length; i++) {
incorrects[i].style.backgroundColor = 'red';
document.querySelector('#resultQ1').innerHTML = 'Wrong :(';
}
}
function Q2() {
if (secondQ.value.toLowerCase() == "yes") {
secondQ.style.backgroundColor = 'green';
document.querySelector('#resultQ2').innerHTML = 'Correct!';
}
else {
secondQ.style.backgroundColor = 'red';
document.querySelector('#resultQ2').innerHTML = 'Wrong :(';
}
}
document.addEventListener('DOMContentLoaded', function() {
let correct = document.querySelector('.correct');
correct.addEventListener('click', correct);
let incorrects = document.querySelectorAll('.incorrect');
incorrects.addEventListener('click', Q1wrong);
let secondQ = document.querySelector('#check');
secondQ.addEventListener('click', Q2);
});
<
/script>
<body>
<div class="jumbotron">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<h3>What is Dwayne "The Rock" Johnson's real middle name? </h3>
<button class='incorrect'>Johnsons</button>
<button class='incorrect'>Pebble</button>
<button class='correct'>Douglas</button>
<button class='incorrect'>Teetsy</button>
<button class='incorrect'>Lewis</button>
<p id='resultQ1'></p>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<h3>Do you smell what The Rock is cooking?</h3>
<input type='text'>
<button id='check' class="input">Check answer</button>
<p id='resultQ2'></p>
</div>
</div>
</body>

The correct event name is "DOMContentLoaded". You are writting "DomContentLoaded".

I updated your js code with some changes and comments. I've tested here and now it works.
//How you use it in more than one function Define it as a global var
let incorrects, correct;
function Q1correct() {
correct.style.backgroundColor = 'green';
document.querySelector('#resultQ1').innerHTML = 'Correct!';
}
function Q1wrong() {
for (let i = 0; i < incorrects.length; i++) {
incorrects[i].style.backgroundColor = 'red';
document.querySelector('#resultQ1').innerHTML = 'Wrong :(';
}
}
function Q2() {
if (secondQ.value.toLowerCase() == "yes") {
secondQ.style.backgroundColor = 'green';
document.querySelector('#resultQ2').innerHTML = 'Correct!';
}
else {
secondQ.style.backgroundColor = 'red';
document.querySelector('#resultQ2').innerHTML = 'Wrong :(';
}
}
document.addEventListener('DOMContentLoaded', function () {
correct = document.querySelector('.correct');
correct.addEventListener('click', Q1correct);
//querySelectorAll returns an array, so we need to loop into it
incorrects = document.querySelectorAll('.incorrect');
incorrects.forEach(btn => {
btn.addEventListener('click', Q1wrong)
})
let secondQ = document.querySelector('#check');
secondQ.addEventListener('click', Q2);
});

First of all you have a typo 'DOMContentLoaded'.
Also you need to attach event listener to an individual item. Instead you've attached the click listener to an NodeLists which won't work.
Also you've declared some variable inside DOMContentLoaded and used them inside other function. Which of course won't work because of functional scoping.
You can check this working code to get some idea.
<body>
<div class="jumbotron">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<h3>What is Dwayne "The Rock" Johnson's real middle name? </h3>
<button class='incorrect'>Johnsons</button>
<button class='incorrect'>Pebble</button>
<button class='correct'>Douglas</button>
<button class='incorrect'>Teetsy</button>
<button class='incorrect'>Lewis</button>
<p id='resultQ1'></p>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<h3>Do you smell what The Rock is cooking?</h3>
<input type='text' id="secondValue">
<button id='check' class="input">Check answer</button>
<p id='resultQ2'></p>
</div>
</div>
<script>
function Q1correct() {
let correct = document.querySelector('.correct');
correct.style.backgroundColor = 'green';
document.querySelector('#resultQ1').innerHTML = 'Correct!';
}
function Q1wrong() {
this.style.backgroundColor = 'red';
document.querySelector('#resultQ1').innerHTML = 'Wrong :(';
}
function Q2() {
const secondValue = document.querySelector('#secondValue');
const secondQ = document.querySelector('#check');
if (secondValue.value.toLowerCase() == "yes") {
secondQ.style.backgroundColor = 'green';
document.querySelector('#resultQ2').innerHTML = 'Correct!';
}
else {
secondQ.style.backgroundColor = 'red';
document.querySelector('#resultQ2').innerHTML = 'Wrong :(';
}
}
document.addEventListener('DOMContentLoaded', function() {
let correct = document.querySelector('.correct');
correct.addEventListener('click', Q1correct);
let incorrects = document.querySelectorAll('.incorrect');
incorrects.forEach(incorrect => incorrect.addEventListener('click', Q1wrong))
let secondQ = document.querySelector('#check');
secondQ.addEventListener('click', Q2);
});
</script>
</body>

Related

How to delete a DOM element from an array after you've clicked on it?

I was making a simple to-do list. You submit itens from an input and they go to the To-DO section. When you click over them they go to the 'Done' section. And when you click on them again, they vanish forever. It was all working fine.
But I realized the doneItens array kept growing in length, which I wanted to optimize. So I came up with this line of code
doneItens.splice(i, 1);
which goes inside an onclick event, which you can see in the code inside the deleteDone function.
That gives the error, though,
Error:{
"message": "Uncaught TypeError: doneItens.splice is not a function"
If I put it outside and below the onclick event it also doesn't work. How can I do it?
var input = document.getElementById('play');
var toDo = document.getElementsByTagName('ol')[0];
var done = document.getElementById('done');
function handleSubmit(event) {
event.preventDefault();
const newItem = document.createElement('li');
newItem.setAttribute('class', 'item');
newItem.append(input.value);
toDo.append(newItem);
input.value='';
deleteItem();
}
function deleteItem() {
const toBeDone = document.getElementsByClassName('item');
for(let i = 0; i < toBeDone.length; i++) {
toBeDone[i].onclick = () => {
appendItemDone(toBeDone[i]);
toBeDone[i].style.display = 'none';
deleteDone();
}
}
}
function appendItemDone(item) {
const newDone = document.createElement('li');
newDone.setAttribute('class', 'feito')
newDone.append(item.innerText);
done.append(newDone);
}
function deleteDone() {
const doneItens = document.getElementsByClassName('feito');
console.log('done length', doneItens.length)
for (let i = 0; i < doneItens.length; i++) {
doneItens[i].onclick = () => {
doneItens[i].style.display = 'none';
doneItens.splice(i, 1);
}
}
}
<div id='flex'>
<form class='form' onsubmit='handleSubmit(event)'>
<input placeholder='New item' type='text' id='play'>
<button>Send</button>
</form>
<div id='left'>
<h1 id='todo' >To-do:</h1>
<p class='instruction'><i>(Click over to mark as done)</i></p>
<ol id='here'></ol>
</div>
<div id='right'>
<h1>Done:</h1>
<p class='instruction'><i>(Click over to delete it)</i></p>
<p id='placeholder'></p>
<ol id='done'></ol>
</div>
</div>
With the use of JavaScript DOM API such as Node.removeChild(), Element.remove() and Node.parentNode, your task can be solved with this code:
const input = document.getElementById('play');
const todo = document.getElementById('todo');
const done = document.getElementById('done');
function handleSubmit(event) {
event.preventDefault();
// create new "todo" item
const newTodo = document.createElement('li');
newTodo.textContent = input.value;
todo.append(newTodo);
// clean the input field
input.value = '';
// listen to "click" event on the created item to move it to "done" section
newTodo.addEventListener('click', moveToDone);
}
function moveToDone(event) {
// remove "click"-listener to prevent event listener leaks
event.target.removeEventListener('click', moveToDone);
// move clicked todo-element to "done" section
const newDone = event.target.parentNode.removeChild(event.target);
done.append(newDone);
// listen to "click" event on the moved item to then completely delete it
newDone.addEventListener('click', removeFromDone);
debugElementsLeak();
}
function removeFromDone(event) {
// remove "click"-listener to prevent event listener leaks
event.target.removeEventListener('click', removeFromDone);
// complete remove clicked element from the DOM
event.target.remove();
debugElementsLeak();
}
function debugElementsLeak() {
const todoCount = todo.childElementCount;
const doneCount = done.childElementCount;
console.log({ todoCount, doneCount });
}
<div id="flex">
<form class="form" onsubmit="handleSubmit(event)">
<input placeholder="New item" type="text" id="play">
<button>Add item</button>
</form>
<div id="left">
<h1>To-do:</h1>
<p class="instruction"><em>(Click over to mark as done)</em></p>
<ol id="todo"></ol>
</div>
<div id="right">
<h1>Done:</h1>
<p class="instruction"><em>(Click over to delete it)</em></p>
<p id="placeholder"></p>
<ol id="done"></ol>
</div>
</div>
You'll want to use splice,
and then rather than use hidden, 'refresh' the done element by adding all elements in the spliced array.
I've commented my code where I've made changes and why
var input = document.getElementById('play');
var toDo = document.getElementsByTagName('ol')[0];
var done = document.getElementById('done');
function handleSubmit(event) {
event.preventDefault();
const newItem = document.createElement('li');
newItem.setAttribute('class', 'item');
newItem.append(input.value);
toDo.append(newItem);
input.value='';
deleteItem();
}
function deleteItem() {
const toBeDone = document.getElementsByClassName('item');
for(let i = 0; i < toBeDone.length; i++) {
toBeDone[i].onclick = () => {
appendItemDone(toBeDone[i].cloneNode(true));
toBeDone[i].style.display = 'none';
deleteDone();
}
}
}
function appendItemDone(item) {
const newDone = document.createElement('li');
newDone.setAttribute('class', 'feito')
newDone.append(item.innerText);
done.append(newDone);
}
function deleteDone() {
var doneItens = document.getElementsByClassName('feito');
for (let i = 0; i < doneItens.length; i++) {
doneItens[i].onclick = () => {
var splicedArray = spliceFromArray(doneItens,doneItens[i]);// NEW BIT -CALL NEW SPLICE FUNCTION
done.innerHTML=""; // NEW BIT - SET OVERALL DONE TO BLANK ON DELETE
for(var index in splicedArray){// NEW BIT - fOR EACH RETURNED ELEMENT IN THE SPLICE, ADD IT TO THE OVERALL DONE ELEMENT
done.appendChild(splicedArray[index]);
}
}
}
}
function spliceFromArray(arrayInput,element){// NEW BIT - SPLICE FUNCTION THAT RETURNS SPLICED ARRAY
var array = Array.from(arrayInput);
var index = array.indexOf(element);
if(index!=-1){
if(array.length==1 && index == 0){
array = [];
}
else{
array.splice(index,1);
}
}
return array;
}
<div id='flex'>
<form class='form' onsubmit='handleSubmit(event)'>
<input placeholder='New item' type='text' id='play'>
<button>Send</button>
</form>
<div id='left'>
<h1 id='todo' >To-do:</h1>
<p class='instruction'><i>(Click over to mark as done)</i></p>
<ol id='here'></ol>
</div>
<div id='right'>
<h1>Done:</h1>
<p class='instruction'><i>(Click over to delete it)</i></p>
<p id='placeholder'></p>
<ol id='done'></ol>
</div>
</div>

Use onchange function elements declared in select tag in another function also?

I am trying to create a Button which when clicked will display all the colored notes. But the issue is color of the note is stored in local storage using an onchange function. This code shows how it is stored and how it is called
function showNote2() {
console.log("Show");
let note = localStorage.getItem("notes");
if(note == null){
noteData = []
// message.innerText = "Please Add a Note"
}
else{
noteData = JSON.parse(note);
};
let showBox = "";
noteData.forEach(function show(element, index) {
let color1 = localStorage.getItem(`clr${index}`);
showBox += `<div class="noteCard my-2 mx-2 card" id="cardID" style="width: 18rem;">
<select id="mySelect${index}" class="clr-btn" style="text-align:center" onchange="changeColor(${index})">
<option id="bckgrnd-clr" value="white">Background Color</option>
<option id="clrR" value="Red">Red</option>
<option id="clrG" value="Green">Green</option>
<option id="clrB" value="Blue">Blue</option>
</select>
<div class="card-body" id="card${index}" style="background-color:${color1}">
<h5 class="cardtitle">Note
${index + 1}
</h5>
<p class="card-text">
${element}
</p>
<button id="${index}" onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</a>
</div>
</div> `
});
let showNote3 = document.getElementById("notes2");
if(noteData.length != 0){
showNote3.innerHTML = showBox;
}else{
showNote3.innerHTML = "Please add a Note"
};
};
This is the code of onchange=changeColor function:
function changeColor(index) {
console.log("Change");
let note = localStorage.getItem("notes");
if(note != null ){
let colorApply = document.getElementById(`card${index}`);
console.log(colorApply);
let elm1 = document.getElementById(`mySelect${index}`);
console.log(elm1);
let color = elm1.options[elm1.selectedIndex].value;
colorApply.style.backgroundColor = color;
localStorage.setItem(`clr${index}`, color)
}
else{
`Note is Empty`;
};
};
This is the code that I wrote for displaying all the colored notes. This is half written now but even in half-written it is not working: Here is the code:
function displayClrNote() {
console.log("Display");
let displayBtn = document.getElementById("colored-btn")
.addEventListener("click",function (e){
console.log("Clicked",e);
let color1 = localStorage.getItem(`clr${index}`);
console.log(color1)
let clr1 = document.getElementById("clrR");
console.log(clr1)
let clr2 = document.getElementById("clrG");
let clr3 = document.getElementById("clrB");
if(color == clr1,clr2,clr3 ){
console.log("Yes");
}
else{
return "Not found"
}
})
}
When I tried, console.log(color1) in the displayColorNote function the value is returned "null" and when I use Console.log(color1) in showNote2 function, it works great.I think the reason is set item is done in the change color function which is only triggered on Onchange and I need help with how to find a way to access color stored in local storage?
Use arrow function expressions
By using the arrow function syntax in your .addEventListener() you can be able to read datas from localStorage
function displayClrNote() {
console.log("Display");
let displayBtn = document.getElementById("colored-btn").addEventListener("click",evt=>{
console.log("Clicked",evt);
let color1 = localStorage.getItem(`clr${index}`);
console.log(color1)
let clr1 = document.getElementById("clrR");
console.log(clr1)
let clr2 = document.getElementById("clrG");
let clr3 = document.getElementById("clrB");
if(color == clr1,clr2,clr3 ){
console.log("Yes");
}
else{
return "Not found"
}
})
}

Why is if...else statement only compares single word values?

I am making a quiz app that will basically fetch the questions and answers from an API and display it to the webpage. It works fine, but the error handling isn't working. I have a if...else statement that will check if a user has selected the right answer, and if they did, play a sound and display "Nice job" to the user. If they did not, then tell the user that they need to try again. The behavior that I'm getting is very weird. Sometimes when I have chose the correct answer, it says it is not correct. It happens when there is spaces within the answer. For single words such as "true", "false" or "Hello" works fine. I logged the answer to the console stored in a variable called answer_container, when I logged it to the console, the answer and my choice are exactly the same. I have tried using === and == operators to see if that would work, but the result is the same. I have posted the full code including my HTML so that you can see what it is happening. Note it took me couple of tries to get the weird behavior to display.
Here is what I have tried:
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function(choices) {
html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
} else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function() {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function() {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>
You're using the expression select_answer == answer_container to determine if the choice is the correct answer.
select_answer comes from the value attribute of the option you've selected. However, when an answer value contains whitespace, HTML interprets only up to the first whitespace as the "value". When answers like North America come up, the option's value attribute is only North.
When generating your options in your HTML, you need to properly encapsulate them in double quotes ", like so:
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
Tangential, but it would probably be cleaner if you generated your elements with document.createElement() and Node.appendChild(); in this instance the quotes required to properly set the value attribute on each option would have been added for you.
Nice game!
The issue here is the text is getting truncated on whitespace in the HTML, so the value you're comparing it too doesn't match.
You need quotes in the HTML option to preserve white space.
<option value=${choices} <- picks the first word
<option value="${choices}" <- allows the whole string with spaces
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
console.log(toJS)
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function (choices) {
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function () {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function () {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
console.log(select_answer, answer_container)
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>

How can I compare scores using if statement and .innerText?

I'm trying to make a Ping Pong scoreKeeper. Everything is done except the part where the scores are compared and a winner is declared. I'm trying to use the if statement to compare the innerText of two variables and whether their scores match or not. But it's not working.
Here's the Javascript and HTML code I've written.
const p1Score = document.querySelector("#p1Score")
const p2Score = document.querySelector("#p2Score")
const increaseP1Score = document.querySelector("#increaseP1Score")
const increaseP2Score = document.querySelector("#increaseP2Score")
const resetScore = document.querySelector("#resetScore")
const scoreKeeper = document.querySelector("#scoreKeeper")
increaseP1Score.addEventListener('click', function(event) {
p1Score.innerText++
// if (p1Score.innerText == 5 && p1Score.innerText > p2Score.innerText) {
// console.log("Here it works!")
})
increaseP2Score.addEventListener('click', function() {
p2Score.innerText++
})
resetScore.addEventListener('click', function() {
p1Score.innerText = 0;
p2Score.innerText = 0;
})
if (p1Score.innerText == 5 && p1Score.innerText > p2Score.innerText) {
console.log("Working!")
}
<div id="container">
<header id="header">
<h1 id="scoreKeeper">Current Score: <span id="p1Score">0</span> to <span id="p2Score">1</span></h1>
</header>
<footer id="footer">
<button id="increaseP1Score">+1 Player One</button>
<button id="increaseP2Score">+1 Player Two</button>
<button id="resetScore">Reset</button>
</footer>
</div>
You'll see a comment in my JS code. When I try to compare the values there, it somehow works. But I don't know why it doesn't work outside the event listener.
const p1Score = document.querySelector("#p1Score")
const p2Score = document.querySelector("#p2Score")
const increaseP1Score = document.querySelector("#increaseP1Score")
const increaseP2Score = document.querySelector("#increaseP2Score")
const resetScore = document.querySelector("#resetScore")
const scoreKeeper = document.querySelector("#scoreKeeper")
increaseP1Score.addEventListener('click', function(event) {
p1Score.innerText++
checkScore();
// if (p1Score.innerText == 5 && p1Score.innerText > p2Score.innerText) {
// console.log("Here it works!")
})
increaseP2Score.addEventListener('click', function() {
p2Score.innerText++
checkScore();
})
resetScore.addEventListener('click', function() {
p1Score.innerText = 0;
p2Score.innerText = 0;
})
function checkScore(){
if (p1Score.innerText == 5 && p1Score.innerText > p2Score.innerText) {
//console.log("Working!")
alert("working!");
}
}
<div id="container">
<header id="header">
<h1 id="scoreKeeper">Current Score: <span id="p1Score">0</span> to <span id="p2Score">1</span></h1>
</header>
<footer id="footer">
<button id="increaseP1Score">+1 Player One</button>
<button id="increaseP2Score">+1 Player Two</button>
<button id="resetScore">Reset</button>
</footer>
</div>
Your if statement is just running once when the page loads. You could put the functionality... in a function like checkScore() above and call it when you increment the scores. This is more re-usable and a better solution to hard-coding it in each incrementer.

How can I change the visible / hidden property of a button with javascript?

On my page I have the following theme change buttons:
<button class="small theme" name="darkBlue" onclick="setThemeColor(this)">
<span style="color: white; font-weight: bold;">#</span>
</button>
<button class="small theme" name="black" onclick="setThemeColor(this)">
<span style="color:black; font-weight:bold;">#</span>
</button>
I have this javascript:
<script type="text/javascript">
if (localStorage.themeColor) {
document.getElementsByTagName('html')[0].className = localStorage.themeColor;
}
function setThemeColor(button) {
localStorage.themeColor = button.name;
document.getElementsByTagName('html')[0].className = button.name;
var themeButtons = document.querySelectorAll(".theme");
for (var themeButton in themeButtons) {
themeButtons[themeButton].disabled = false;
}
button.disabled = true;
}
</script>
This always shows the two buttons but I would like to so that instead of the
current button being disabled then the button is not visible. Can someone
suggest how I could do this?
function setThemeColor(button) {
localStorage.themeColor = button.name;
document.getElementsByTagName('html')[0].className = button.name;
var themeButtons = document.querySelectorAll(".theme");
for (var themeButton in themeButtons) {
themeButtons[themeButton].disabled = false; // Re-included from original code
themeButtons[themeButton].style.visibility="visible" // Corrected from original answer
}
button.disabled = true;
button.style.visibility="hidden" // Added/Moved from above after noted I'd messed up the logic
}

Categories

Resources