++ a number when two outputs are the same - javascript

Tales game where you select heads or tails and then the computer will select heads or tails and then a random output will be put on the screen if you selected the right one it will add one point to you or the computer or both the first one to five wins. I'm having problem adding the points to ‘thePlayersPoints’ and ‘theComputerPoints’. The outcome I what is where when they equal it will add a point. but what's happening is because it's a click function is it will only Add them if the value is already on the page. What I mean is if you click heads an heads comes up it won't add it until you click it again.
The function that tries to add the points start at line 67.
//Btns
let btn = document.querySelectorAll('button')
let HeadsBtn = document.querySelector('.heads')
let TailsBtn = document.querySelector('.talis')
let output = document.querySelector('.output')
//Player
let PlayersChoice = document.querySelector('.PlayersChoice')
let ThePlayersPoints = document.querySelector('.ThePlayersPoints')
//computer
let ComputerChoice = document.querySelector('.ComputerChoice')
let TheComputersPoints = document.querySelector('.TheComputersPoints')
//winner
let winner = document.querySelector('.winner')
//headsAndTails
let player = 0
let computer = 0
//get The output.
let btnContaner = document.querySelector('.btnCon')
btnContaner.addEventListener('click', pinkingOne)
function pinkingOne(TheOutput){
let random = Math.floor(Math.random() * 2)
if(random === 0){
TheOutput = 'Tails'
}else{
TheOutput = 'Heads'
}
output.innerText = `${ TheOutput}`
}
//Adds Heads to Player selected.
HeadsBtn.addEventListener('click', function(){
PlayersChoice.innerHTML = 'Heads'
})
//Adds Tails to Player selected.
TailsBtn.addEventListener('click',function(pick){
pick ='Tails'
PlayersChoice.innerHTML = `${pick}`
})
//computers pinking heads or tails
btnContaner.addEventListener('click',computersPick)
function computersPick(pick){
let random = Math.floor(Math.random() * 2)
if(random === 1){
pick = 'Heads'
}else{
pick = 'Talis'
}
ComputerChoice.innerText = `${pick}`
}
//adding the points to the player and computer
HeadsBtn.addEventListener('click',function(){
if(PlayersChoice.innerHTML === output.innerHTML){
ThePlayersPoints.innerHTML++
}else{
if (ComputerChoice.innerHTML === output.innerHTML){
TheComputersPoints.innerHTML++
}
}
})
TailsBtn.addEventListener('click',function(){
if(PlayersChoice.innerHTML === output.innerHTML){
ThePlayersPoints.innerHTML++
}else{
if (ComputerChoice.innerHTML === output.innerHTML){
TheComputersPoints.innerHTML++
}
}
})
//^^^^^^^adding the points to the player and computer ^^^^^^^^
//outputing the winner.
function andTheWinnerIs(){
let Tbtn = document.querySelector('#Tails')
let Hbtn = document.querySelector('#Heads')
Tbtn.addEventListener('click',addforplayer)
Hbtn.addEventListener('click',addforplayer)
//outputing the winner
if ( ThePlayersPoints.innerHTML == 5 && TheComputersPoints.innerHTML == 5){
winner.innerHTML = `It's a Tie`;
} else if (ThePlayersPoints.innerHTML == 5){
winner.innerHTML = `You Win!!!`;
} else if (TheComputersPoints.innerHTML == 5){
winner.innerHTML = `Computer Wins!!!`;
}
}
html{
background-color:rgba(128, 128, 128, 0.712);
margin:0;
padding:0;
top:0;
}
body {
overflow: hidden; /* Hide scrollbars */
}
.PlayerSelected{
position: relative;
right: 150px;
font-family: 'Quantico', sans-serif;
}
.ComputerSelected{
position: relative;
left: 150px;
top: -43px;
font-family: 'Quantico', sans-serif;
}
.PlayerPoints{
position: relative;
left: -110px;
top:109px;
font-family: 'Quantico';
}
.ComputerPoints{
position: relative;
right: -103px;
top: 60px;
font-family: 'Quantico';
}
.PlayersChoice{
color: rgba(19, 107, 207, 0.836);
background-color: black;
width: 0px;
position: relative;
left: -80px;
top: -37px
}
#Theoutput{
font-size:xx-large;
position: relative;
top: -120px
}
#ThePlayersPoints{
position: relative;
top:23.5px;
width:10px;
left:-75px;
font-family: 'Quantico';
}
#TheComputersPoints{
position: relative;
left: 150px;
top: -5px;
font-family: 'Quantico';
}
.ComputerChoice{
position: relative;
right: -250px;
color:red;
top: -90px
}
#Thewinner{
background-color:aqua;
width: 200px;
}
.H1{
font-family: 'Kaushan Script', cursive;
text-shadow: 2px 2px rgba(255, 0, 0, 0.589);
}
#Heads{
outline: none;
border: none;
font-size: xx-large;
cursor: pointer;
}
#Tails{
outline: none;
border: none;
font-size: xx-large;
cursor: pointer;
}
#Tails:hover{
font-size: 50px;
background-color:rgba(0, 26, 255, 0.534);
box-shadow: 5px 10px gray;
}
#Heads:hover{
font-size: 50px;
background-color:rgba(255, 0, 0, 0.664);
box-shadow: -5px 10px gray;
}
.pickHeadsOrTalis{
font-family: 'Staatliches';
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Light Switching</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Kaushan+Script&display=swap');
</style>
<style>
#import url('https://fonts.googleapis.com/css2?family=Quantico&display=swap');
</style>
<style>
#import url('https://fonts.googleapis.com/css2?family=Staatliches&display=swap');
</style>
</head>
<body>
<center>
<h1 class='H1'>First Player to 5 points wins!</h1>
<h3 class='PlayerSelected'>Player selected:</h3>
<div id='PlayersChoice' id='o' class='PlayersChoice'></div>
<h3 class='ComputerSelected' >Computer selected:</h3>
<div id='ComputerChoice' class='ComputerChoice '></div>
<h4 class='PlayerPoints' >Player:</h4>
<h4 class='ComputerPoints'> Computer: </h4>
<div class="PlayersAndComputersPoints">
<div id='ThePlayersPoints' class="ThePlayersPoints">0</div>
<div id='TheComputersPoints' class="TheComputersPoints">0</div>
</div>
<div id='Theoutput' class="output"></div>
<h1 id='Thewinner' class="winner"></h1>
<h1 class="pickHeadsOrTalis">Pick heads or tails?</h1>
<div id='allBtn' class="btnCon">
<button id='Heads' class="heads">Heads</button> <button id='Tails' class='talis'>Tails</button>
</div>
</center>
<script src="app.js"></script>
</body>
</html>

First of all, you are adding in two different 'click' event listeners in the buttons and they should be combined into one.
Secondly the if statement in the second event listener will only ever get to evaluate the computer's choice if the player's choice doesn't match. You need to remove the else between the player evaluation and the computer's evaluation and just do two different if statements for each player.
You also had two extra unneeded event listeners on the .btnContainer element. You can just call those functions all in the one button click event.
You will also want to disable the buttons after a game is won and add in a reset button to start the game over.
I hope that this helps
See snippet below for the changes I made:
//Btns
let btn = document.querySelectorAll('button')
let HeadsBtn = document.querySelector('.heads')
let TailsBtn = document.querySelector('.talis')
let output = document.querySelector('.output')
//Player
let PlayersChoice = document.querySelector('.PlayersChoice')
let ThePlayersPoints = document.querySelector('.ThePlayersPoints')
//computer
let ComputerChoice = document.querySelector('.ComputerChoice')
let TheComputersPoints = document.querySelector('.TheComputersPoints')
//winner
let winner = document.querySelector('.winner')
//headsAndTails
let player = 0
let computer = 0
//get The output.
let btnContaner = document.querySelector('.btnCon')
//btnContaner.addEventListener('click', pinkingOne)
function pinkingOne() {
let TheOutput;
let random = Math.floor(Math.random() * 2)
if (random === 0) {
TheOutput = 'Tails'
} else {
TheOutput = 'Heads'
}
output.innerText = `${ TheOutput}`
}
//Adds Heads to Player selected.
// HeadsBtn.addEventListener('click', function(){
//PlayersChoice.innerHTML = 'Heads'
//})
//Adds Tails to Player selected.
//TailsBtn.addEventListener('click',function(pick){
// pick ='Tails'
// PlayersChoice.innerHTML = `${pick}`
//})
//computers pinking heads or tails
//btnContaner.addEventListener('click',computersPick)
function computersPick() {
let pick;
let random = Math.floor(Math.random() * 2)
if (random === 1) {
pick = 'Heads'
} else {
pick = 'Tails'
}
ComputerChoice.innerText = `${pick}`
}
//adding the points to the player and computer
HeadsBtn.addEventListener('click', function() {
PlayersChoice.innerHTML = 'Heads'
pinkingOne();
computersPick();
if (PlayersChoice.innerHTML === output.innerHTML) {
player++
ThePlayersPoints.innerHTML = player;
}
// else {
if (ComputerChoice.innerHTML === output.innerHTML) {
computer++
TheComputersPoints.innerHTML = computer
}
//}
if (player === 5 || computer === 5) {
andTheWinnerIs();
}
})
TailsBtn.addEventListener('click', function() {
PlayersChoice.innerHTML = 'Tails'
pinkingOne();
computersPick();
if (PlayersChoice.innerHTML === output.innerHTML) {
player++
ThePlayersPoints.innerHTML = player;
}
// else {
if (ComputerChoice.innerHTML === output.innerHTML) {
computer++
TheComputersPoints.innerHTML = computer
}
//}
if (player === 5 || computer === 5) {
andTheWinnerIs();
}
})
//^^^^^^^adding the points to the player and computer ^^^^^^^^
//outputing the winner.
function andTheWinnerIs() {
//let Tbtn = document.querySelector('#Tails')
//let Hbtn = document.querySelector('#Heads')
//Tbtn.addEventListener('click', addforplayer)
//Hbtn.addEventListener('click', addforplayer)
//outputing the winner
if (player === 5 && computer == 5) {
winner.innerHTML = `It's a Tie`;
} else if (player === 5) {
winner.innerHTML = `You Win!!!`;
} else if (computer === 5) {
winner.innerHTML = `Computer Wins!!!`;
}
}
html {
background-color: rgba(128, 128, 128, 0.712);
margin: 0;
padding: 0;
top: 0;
}
body {
/* overflow: hidden;
Hide scrollbars */
}
.PlayerSelected {
position: relative;
right: 150px;
font-family: 'Quantico', sans-serif;
}
.ComputerSelected {
position: relative;
left: 150px;
top: -43px;
font-family: 'Quantico', sans-serif;
}
.PlayerPoints {
position: relative;
left: -110px;
top: 109px;
font-family: 'Quantico';
}
.ComputerPoints {
position: relative;
right: -103px;
top: 60px;
font-family: 'Quantico';
}
.PlayersChoice {
color: rgba(19, 107, 207, 0.836);
background-color: black;
width: 0px;
position: relative;
left: -80px;
top: -37px
}
#Theoutput {
font-size: xx-large;
position: relative;
top: -120px
}
#ThePlayersPoints {
position: relative;
top: 23.5px;
width: 10px;
left: -75px;
font-family: 'Quantico';
}
#TheComputersPoints {
position: relative;
left: 150px;
top: -5px;
font-family: 'Quantico';
}
.ComputerChoice {
position: relative;
right: -250px;
color: red;
top: -90px
}
#Thewinner {
background-color: aqua;
width: 200px;
}
.H1 {
font-family: 'Kaushan Script', cursive;
text-shadow: 2px 2px rgba(255, 0, 0, 0.589);
}
#Heads {
outline: none;
border: none;
font-size: xx-large;
cursor: pointer;
}
#Tails {
outline: none;
border: none;
font-size: xx-large;
cursor: pointer;
}
#Tails:hover {
font-size: 50px;
background-color: rgba(0, 26, 255, 0.534);
box-shadow: 5px 10px gray;
}
#Heads:hover {
font-size: 50px;
background-color: rgba(255, 0, 0, 0.664);
box-shadow: -5px 10px gray;
}
.pickHeadsOrTalis {
font-family: 'Staatliches';
}
<!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">
<link rel="stylesheet" href="style.css">
<title>Light Switching</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Kaushan+Script&display=swap');
</style>
<style>
#import url('https://fonts.googleapis.com/css2?family=Quantico&display=swap');
</style>
<style>
#import url('https://fonts.googleapis.com/css2?family=Staatliches&display=swap');
</style>
</head>
<body>
<center>
<h1 class='H1'>First Player to 5 points wins!</h1>
<h3 class='PlayerSelected'>Player selected:</h3>
<div id='PlayersChoice' id='o' class='PlayersChoice'></div>
<h3 class='ComputerSelected'>Computer selected:</h3>
<div id='ComputerChoice' class='ComputerChoice '></div>
<h4 class='PlayerPoints'>Player:</h4>
<h4 class='ComputerPoints'> Computer: </h4>
<div class="PlayersAndComputersPoints">
<div id='ThePlayersPoints' class="ThePlayersPoints">0</div>
<div id='TheComputersPoints' class="TheComputersPoints">0</div>
</div>
<div id='Theoutput' class="output"></div>
<h1 id='Thewinner' class="winner"></h1>
<h1 class="pickHeadsOrTalis">Pick heads or tails?</h1>
<div id='allBtn' class="btnCon">
<button id='Heads' class="heads">Heads</button> <button id='Tails' class='talis'>Tails</button>
</div>
</center>
<script src="app.js"></script>
</body>
</html>

Related

How to reload all kinds of functions and all HTML code in JavaScript to restart a game?

Clicking on the Home button at the end of this project brings it to the beginning, but no function is reset. Level buttons are not also being enabled anew. If I enable those level buttons by writing some extra code for enabling, then the number of buttons given for each level will be doubled after selecting the level. In other words, for the first time due to selecting the basic level, there were 4 options, But when I click on the last home button and then select the medium level to play the game from the beginning, it becomes 16 options instead of 8.
//VARIABLE DECLARATION PART
let frontpage = document.querySelector(".front-page");
let playbutton = document.querySelector(".play");
let levelpage = document.querySelector(".levelpg");
let startbtn = document.querySelector(".startbtn");
let maingame = document.querySelector(".maingame");
let easybtn = document.querySelector(".easy");
let mediumbtn = document.querySelector(".medium");
let hardbtn = document.querySelector(".hard");
let nextbtn = document.querySelector(".nextbtn");
let pagecount = document.querySelector('.gamepagecount');
let getnumberdiv = document.querySelector('.numberbtn').children;
let resultpg = document.querySelector('.resultpage');
let backhome = document.querySelector('.backhome');
let finalscore = document.querySelector('.score');
let resulttext = resultpg.children[1];
let changeimg = document.querySelector('.resultpage img');
// PLAYBUTTON CLICK
playbutton.addEventListener("click", () => {
frontpage.classList.add("hidden");
levelpage.classList.remove("hidden");
levelpage.classList.add("visibility");
});
//GAME START FUNCTION
function startGame(level) {
if (level == "easy") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
easybtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 10`;
nextbtn.disabled = true
levelChange(4);
gameInterfaceChange()
mainGame(10);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(4)
pageCount(10);
mainGame(10);
})
});
}
else if (level == "medium") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
mediumbtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 15`;
nextbtn.disabled = true
levelChange(8);
gameInterfaceChange();
maingame.style.top = "20%";
mainGame(20);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(8)
pageCount(15)
mainGame(20);
})
});
}
else if (level == "hard") {
mediumbtn.disabled = true;
hardbtn.disabled = true;
easybtn.disabled = true;
hardbtn.classList.add('levelcolor');
startbtn.addEventListener("click", () => {
pagecount.innerHTML = `1 of 20`;
nextbtn.disabled = true
levelChange(12);
gameInterfaceChange();
maingame.style.top = "12%";
mainGame(30);
//NEXTBUTTON FUNCTION
nextbtn.addEventListener('click', () => {
enableBtn(12)
pageCount(20)
mainGame(30);
})
});
}
}
//PAGE SLIDING FUNCTION
function gameInterfaceChange() {
levelpage.classList.remove("hidden");
levelpage.classList.add("hidden");
maingame.classList.remove("hidden");
maingame.style.top = "25%";
maingame.classList.add("visibility");
}
// FUNCTION OF RANDOM INPUTING NUMBER IN DIV
function mainGame(maxnum) {
let numboxlen = getnumberdiv.length;
let wrongnum = Math.floor(Math.random() * maxnum) + 1;
let getnumber = [];
//DUPLICATE RANDOM NUMBER CHECKING
for (let i = 0; i < numboxlen; i++) {
let check = getnumber.includes(wrongnum);
if (check === false) {
getnumber.push(wrongnum);
}
else {
while (check === true) {
wrongnum = Math.floor(Math.random() * maxnum) + 1;
check = getnumber.includes(wrongnum);
if (check === false) {
getnumber.push(wrongnum);
}
}
}
}
// NUMBER PUTTING IN InnerHtml
for (var j = 0; j < numboxlen; j++) {
if (getnumber[j] < 10) {
getnumberdiv[j].innerHTML = '0' + getnumber[j];
}
else {
getnumberdiv[j].innerHTML = getnumber[j];
}
}
}
// BUTTON ADDING ACCORDING TO THE LEVEL
function levelChange(divnum) {
for (let index = 0; index < divnum; index++) {
let newBtn = document.createElement('button');
let newbtnNode = document.createTextNode('');
newBtn.appendChild(newbtnNode);
let gamebtn = document.getElementById('numbrbtn');
gamebtn.appendChild(newBtn);
newBtn.setAttribute("onclick", `numberClick(${index},${divnum})`);
}
}
//RIGHT - WRONG CHECKING FUNTION
var right = 0;
var wrong = 0;
function numberClick(index, divnum) {
let rightnumberindex = Math.floor(Math.random() * divnum);
if (index == rightnumberindex) {
nextbtn.disabled = false
right++;
//RIGHT AND WRONG BACKGROUND ADDING AND BUTTON DISABLE
getnumberdiv[index].classList.add("rightans");
for (let i = 0; i < divnum; i++) {
getnumberdiv[i].disabled = true;
}
}
else {
nextbtn.disabled = false
wrong++;
//RIGHT AND WRONG BACKGROUND ADDING AND BUTTON DISABLE
getnumberdiv[rightnumberindex].classList.add("rightans");
getnumberdiv[index].classList.add("wrongans");
for (let i = 0; i < divnum; i++) {
getnumberdiv[i].disabled = true;
}
}
}
// BUTTON ENABLE ON NEXT BUTTION CLICK
function enableBtn(divnum) {
for (let i = 0; i < divnum; i++) {
nextbtn.disabled = true
getnumberdiv[i].disabled = false;
getnumberdiv[i].classList.remove("wrongans");
getnumberdiv[i].classList.remove("rightans");
}
}
//PAGE COUNTING ACCORDING TO THE LEVEL
let currentpg = 1;
function pageCount(levelPg) {
currentpg++;
if (currentpg <= levelPg) {
if (currentpg == levelPg) {
nextbtn.innerHTML = 'Result'
pagecount.innerHTML = `${currentpg} of ${levelPg}`;
}
else {
pagecount.innerHTML = `${currentpg} of ${levelPg}`;
}
}
else {
result();
}
}
//FINAL RESULT FUNTION
function result() {
maingame.classList.remove("visibility");
maingame.classList.add("hidden");
resultpg.classList.remove('hidden')
resultpg.classList.add('visibility')
if (right > wrong) {
changeimg.setAttribute('src', 'trophy.png')
resulttext.innerHTML = `You Win`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
else if (right == wrong) {
changeimg.setAttribute('src', 'draw.png')
resulttext.innerHTML = `It's Draw`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
else if (right < wrong) {
changeimg.setAttribute('src', 'lose.png')
resulttext.innerHTML = `You Lose`;
finalscore.innerHTML = `Your Right Score is : ${right} out of ${right + wrong}`;
}
}
//BACK TO THE HOME FUNCTION
backhome.addEventListener('click', () => {
frontpage.classList.add("visibility");
frontpage.classList.remove("hidden");
resultpg.classList.add('hidden')
resultpg.classList.remove('visibility')
// enable level button
mediumbtn.disabled = false;
hardbtn.disabled = false;
easybtn.disabled = false;
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
margin-top: 50px;
}
.guessing-game {
position: relative;
color: white;
text-align: center;
margin: auto;
width: 350px;
height: 600px;
border-radius: 25px;
padding: 50px 30px;
background: linear-gradient(to right, #bd3f32, #cb356b);
}
.guessing-game .front-page .front-img {
height: 160px;
text-align: center;
}
.guessing-game .front-page img {
max-height: 100%;
}
.guessing-game .front-page .front-text h1 {
margin-top: 50px;
font-size: 1.8em;
}
.guessing-game .front-page .front-text p {
margin-top: 10px;
font-size: 1em;
}
.guessing-game .front-page .front-text button,
.resultpage button ,
.levelpg .easy,
.levelpg .medium,
.levelpg .hard,
.maingame .nextbtn {
margin-top: 30px;
width: 100%;
color: white;
padding: 15px;
outline: 0;
border: 0;
border-radius: 50px;
font-size: 0.9em;
background-color: #d64d5d;
box-shadow: rgba(17, 17, 26, 0.1) 0px 1px 0px,
rgba(17, 17, 26, 0.144) 0px 8px 24px, rgba(17, 17, 26, 0.1) 0px 16px 48px;
}
.guessing-game .front-page .front-text button:hover,
.maingame .nextbtn:hover,
.resultpage button:hover {
transition: 0.5s;
background-color: #c22f40;
}
/* Level page */
.visiblepg {
position: absolute;
top: 12%;
width: 290px;
}
.levelpg h1 {
margin: 45px 0 40px 0;
font-weight: 600;
font-size: 2.4em;
border: 1px solid white;
}
.levelpg .easy,
.levelpg .medium,
.levelpg .hard {
display: block;
margin-top: 15px;
padding: 12px;
background: white;
font-size: 1em;
border-radius: 10px;
font-weight: 400;
color: #c22f40;
}
.startbtn {
background: transparent;
border: 0;
outline: 0;
}
.levelpg i {
color: white;
margin-top: 50px;
font-size: 70px;
border-radius: 50%;
border: 2px solid transparent;
}
.levelpg i:hover {
background-color: white;
border: 2px solid white;
color: #c22f40;
transition: 0.5s;
}
/* GAME PART */
.maingame .gamepagecount {
background-color: #d64d5d;
color: white;
padding: 4px;
border-radius: 6px;
font-size: 0.8em;
font-weight: 600;
}
.maingame .gametext {
margin-top: 15px;
font-size: 1.2em;
}
.maingame .numberbtn {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.maingame .numberbtn button {
margin-top: 40px;
width: 50px;
height: 50px;
background-color: white;
display: flex;
align-content: space-around;
justify-content: center;
align-items: center;
flex-wrap: wrap;
flex: 1 0 21%;
margin-left: 10px;
border: 0;
outline: 0;
border-radius: 10px;
font-size: 1em;
color: #c22f40;
font-weight: 600;
}
.maingame .numberbtn button:nth-child(1),
.maingame .numberbtn button:nth-child(5),
.maingame .numberbtn button:nth-child(9) {
margin-left: 0;
}
.resultpage h1 {
margin: 0px 0 40px 0;
}
.resultpage img {
margin-top: 45px;
width: 50%;
}
/* PRE DEFINE CSS */
.visibility {
visibility: visiible;
opacity: 2s;
transition: 0.5s;
transform: translateX(0px);
}
.hidden {
visibility: hidden;
opacity: 0;
transition: 0.5s;
transform: translateX(-30px);
}
.levelcolor {
transition: 0.5s;
color: white !important;
background-color: #c22f40 !important;
}
.rightans {
background-color: #27ae60 !important;
color: white !important;
transition: 0.5s;
}
.wrongans {
background-color: #fd4631 !important;
color: white !important;
transition: 0.5s;
}
<!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=Poppins:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap"
rel="stylesheet" />
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"
integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
<title>Guessing Game</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="guessing-game">
<div class="front-page">
<div class="front-img">
<img src="./question.png" alt="" />
</div>
<div class="front-text">
<h1>Guessing Game</h1>
<p>
You just need to chose the right number from the option. If your
guess is right more than wrong , you will win otherwise you will
fail! Let's see how good your sixth sense is!!!
</p>
<button class="play">Let's play</button>
</div>
</div>
<div class="levelpg hidden visiblepg">
<h1>Game level</h1>
<button class="easy" onclick="startGame('easy')">Easy</button>
<button class="medium" onclick="startGame('medium')">Medium</button>
<button class="hard" onclick="startGame('hard')">Hard</button>
<button class="startbtn"><i class="fas fa-play-circle"></i></button>
</div>
<div class="maingame visiblepg hidden">
<p class="gamepagecount">1</p>
<p class="gametext">Guess the number you think is right</p>
<div class="numberbtn" id="numbrbtn"></div>
<button class="nextbtn">Next</button>
</div>
<div class="resultpage levelpg hidden visiblepg">
<img src="" alt="" />
<h1></h1>
<div class="score"></div>
<button class="backhome">Home</button>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
In short, as soon as I click on the home button, I want the game to start anew, all the functions will be reset anew, and the HTML will be reset anew also. I hope my problem is enough clear to understand.
I have solved the problem.
I just add a reload function to solve this problem.
backhome.addEventListener('click', () => {
frontpage.classList.add("visibility");
frontpage.classList.remove("hidden");
resultpg.classList.add('hidden')
resultpg.classList.remove('visibility')
//reload function
window.location.reload();
})

how can i create smooth seeker in my video player like youtube player

I have created a player and I expected it to be smooth as a youtube player. But my player is not that smooth. and it also gives some bug-like
If I mouse down the slider and mousemove it and it slides but after mouse up, it doesn't stop the slide on mousemove and it doesn't give the same result I expected
window.onload = function(){
var music = document.getElementById('music');
music.src = 'https://fr01.mp3snow.com/4d1c6fa75beebf67d9969/Charlie%20Puth%20-%20We%20Don%20t%20Talk%20Anymore%20feat.%20Selena%20Gomez.mp3'
setTimeout(()=>{
var play = document.getElementById('playpause')
//slider for music
var slider = document.getElementById('slider');
//slider Container for slider in music player
var sliderCon = document.getElementById('sliderCon');
var clicked = false;
var body = document.querySelector('body');
var timer = document.getElementById('time');
var durat = document.getElementById('duration');
sliderCon.onmousedown = (e) => {
music.currentTime = (e.offsetX/sliderCon.offsetWidth)*music.duration;
clicked = true;
}
window.onmousemove = (e) =>{
if(clicked == true){
music.currentTime = (e.offsetX/sliderCon.offsetWidth)*music.duration;
if(music.ended == true){
music.play()
}
body.style.cursor = 'grabbing' ;
}
window.onmouseup = () => {
clicked = false;
body.style.cursor = 'inherit';
}
}
function timing(totaltime){
if (totaltime>60){
var minute = Math.floor(totaltime/60)
var second = Math.floor(totaltime%60)
if(minute>9){
var time;
if (second >9){
time = minute+':'+second;
}else{
time = minute+':'+'0'+second;
}
}else if (minute<10){
var time;
if (second >9){
time = '0'+minute+':'+second;
}else{
time = '0'+minute+':'+'0'+second;
}
}
}
else{
if (totaltime<10){
var time = '00:0'+Math.floor(totaltime)
}else{
var time = '00:'+Math.floor(totaltime)
}
}
return time;
}
music.ontimeupdate = () =>{
var sliderWidth = (music.currentTime/music.duration)*100;
slider.style.width = sliderWidth+'%';
timer.innerHTML = timing(music.currentTime)
durat.innerHTML = timing(music.duration)
}
play.onselect = () =>{
document.click();
}
play.onclick = (e) => {
if(music.paused == true || music.ended == true){
music.play();
play.innerHTML = '<i class="fas fa-pause"></i>';
}else if (music.paused == false || music.ended == false){
music.pause();
play.innerHTML = '<i class="fas fa-play"></i>';
}
}
window.onkeydown = (key) => {
if (key.key == 'ArrowRight'){
music.currentTime += 5
}
if (key.key == 'ArrowLeft') {
music.currentTime -= 5
}
if (key.key == ' ') {
if(music.paused == true || music.ended == true){
music.play();
play.innerHTML = 'PAUSE';
}else if (music.paused == false || music.ended == false){
music.pause();
play.innerHTML = 'PLAY';
}
}
if (key.key == 'ArrowUp'){
if(music.volume < 1){
music.volume +=0.1;
}
}
if (key.key == 'ArrowDown'){
if(music.volume > 0.1){
music.volume -=0.1;
}
}
if (key.code == 'NumpadAdd'){
if (music.playbackRate < 2.0){
music.playbackRate += 0.1
}
}
if (key.code == 'NumpadSubtract'){
if (music.playbackRate > 0.1){
music.playbackRate -= 0.1
}
}
if (key.key == 'h'){
music.playbackRate = -1.0;
}
}
},0)
var loaded = document.getElementById('loaded');
console.log(loaded)
music.addEventListener('progress', function(e) {
setTimeout(()=>{
loaded.style.width = Math.round((this.buffered.end(0)/this.duration) * 100)+'%';
},6)
});
}
*{
margin: 0;
padding: 0;
}
body{
background-color: rgba(32, 29, 29, 0.89);
}
.playpause{
color: rgb(255, 248, 248);
left: 22%;
position: relative;
top: 16%;
font-size: 3rem;
font-family: sans-serif;
}
#duration{
color: rgb(255, 248, 248);
text-align: right;
margin-right: 5px;
font-size: 1rem;
font-family: sans-serif;
position: relative;
top: -1rem;
}
#time{
color: rgb(255, 248, 248);
text-align: left;
margin-left: 5px;
font-size: 1rem;
font-family: sans-serif;
}
#fornow{
background-color: rgb(116, 116, 150);
width: 80%;
margin: 50px auto;
height: 150px;
}
.sliderCon{
width: 90%;
margin: 0 auto;
position: relative;
top: 70px;
background-color: rgb(197, 192, 192);
height: 6px;
transition: 0.3s;
}
.slider{
position: relative;
height: 100%;
width: 0%;
transition: 0.3s;
background-color: rgb(228, 54, 54);
}
.sliderCon:hover{
height: 10px;
top: 67px;
cursor: grab;
}
.thumb{
width: 18px;
height: 18px;
background-color: rgb(228, 54, 54);
position: absolute;
margin-left: 98%;
border-radius: 50%;
margin-top: -5px;
transition: 0.3s;
pointer-events: none;
}
.sliderCon:hover .thumb{
margin-left: 97%;
width: 20px;
height: 20px;
}
#loaded{
background-color: rgba(226, 95, 95, 0.616);
position: absolute;
width: 0%;
height: 100%;
}
#loading{
width: 60px;
height: 60px;
background-color: transparent;
margin: 0 auto;
border: 5px solid;
border-color: teal;
transition: 1s;
border-radius: 50%;
animation: load 1s infinite;
animation-fill-mode: both;
border-top-color: tomato;
display: none;
}
#keyframes load{
to{
transform: rotate(360deg);
}
}
.yo{
width: 75px;
height: 75px;
background-color: cyan;
margin: 0 auto;
border-radius: 50%;
position: relative;
}
<!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>Player</title>
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<audio src="./" id="music"></audio>
<div class="player">
<div id="fornow">
<div class="sliderCon" id="sliderCon">
<div id="loaded">
</div>
<div class="slider" id="slider">
<div class="thumb" id="thumb"></div>
</div>
</div>
</div>
<div id="time">00:00</div>
<div id="duration">00:00</div>
<div id="loading">
</div>
<div class="controls">
<div class="backward"></div>
<div class="yo">
<div class="playpause" id="playpause"><i class="fas fa-play"></i></div>
</div>
<div class="forward"></div>
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
It is the Code You can run it and see that it is not smooth as youtube
and it is also declared that youtube player is not flash
so what is the secret of youtube players that I don't know?
Please tell me the answer if anyone knows. sorry This is my personal project so I didn't commented it or name it very well
Thank You

The square does not move JavaScript

I'm creating a game, the div with id "playerDiv" when I hit the space bar it should start going up but it doesn't. So I would like when I hit the space bar the div would go up high.
could you help me? could you also report me the mistakes i made?
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 420 + inc;
player.top = player.top + x;
inc++
playerTimeOut = setTimeout(jump, 50);
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.key === ' ') {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<title>Game</title>
</head>
<body>
<div id="background">
<div id="playerDiv">
</div>
</div>
</body>
<script src="script.js"></script>
</html>
You're not passing the argument in addListener and you're not using correctly the top property, it belongs to style and needs unit , for example px
Also keyCode is deprecated, use key instead
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
player.style.bottom = `${x}px`
inc++
console.log(player.style.bottom)
}
//window.addEventListener("keydown", e => e.key === "(Space Character)" ? jump() : '');
//For snippet only
jump()
setTimeout(() => jump(), 1000)
* {
/* demo */
box-sizing: border-box
}
body {
background-color: #222;
}
#background {
border: solid 2px #ddd;
width: 800px;
height: 500px;
position: relative;
/* demo */
max-width: 100%
}
#playerDiv {
background-color: #aaa;
width: 60px;
height: 80px;
position: absolute;
bottom: 0px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>
Try this:
const player = document.getElementById("playerDiv");
let inc = 0;
let playerTimeOut;
function jump() {
let x = 10 + inc;
let style = window.getComputedStyle(player);
player.style.top = (parseInt(style.getPropertyValue('top'),10) - x) + 'px';
inc++
}
window.addEventListener("keydown", checkKeyPress, false);
function checkKeyPress(key) {
if (key.keyCode == "32") {
jump();
}
}
body {
background-color: #222222;
}
#background {
border: solid 2px #dddddd;
width: 800px;
height: 500px;
}
#playerDiv {
background-color: #aaaaaa;
width: 60px;
height: 80px;
position: relative;
top: 420px;
left: 10px;
}
<div id="background">
<div id="playerDiv">
</div>
</div>

Need a timer or delay function for a small card game

I made a game in JavaScript and it seems to run pretty well. The rules are: There are 2 players who take turns. Draw cards to get points. You can draw multiple cards per turn. You don't get points until you press the End Turn button. If you draw a 2, 5, or 9 then you lose all points for that turn.
Everything works, however, when you draw a 2, 5, or 9 the turn changes before you even get to see the card. So you wouldn't even know if you drew that card.
I want to add a timer or delay function so that when you draw a 2, 5, or 9 it displays that card for a second or two.
And also I want to disable any clicking so you don't accidentally click for the next player.
Here's the link to the page:
https://tneilson08.github.io/cardgame/
var scores, roundScore, activePlayer, gamePlaying;
gamePlaying = true;
init();
// Create the deck
const deck = ["2C", "2S", "2H", "2D", "3C", "3S", "3H", "3D", "4C", "4S", "4H", "4D", "5C", "5S", "5H", "5D", "6C", "6S", "6H", "6D", "7C", "7S", "7H", "7D", "8C", "8S", "8H", "8D", "9C", "9S", "9H", "9D", "10C", "10S", "10H", "10D", "JC", "JS", "JH", "JD", "QC", "QS", "QH", "QD", "KC", "KS", "KH", "KD", "AC", "AS", "AH", "AD"];
// const deck = ["two-club", "two-spade", "two-heart", "two-dia", "three-club", "three-spade", "three-heart", "three-dia"];
// Shuffle the deck
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
shuffleArray(deck);
// Draw cards
function drawCard() {
if (gamePlaying) {
// 1. Draw from the deck and remove with shift()
var card = deck.shift();
// 2. Display the card
var cardDOM = document.querySelector('.card');
cardDOM.style.display = 'block'; // card becomes visible
cardDOM.src = 'img/' + card + '.png'; // determines card drawn
// 3. Determine card value
if (card == "2C" || card == "2S" || card == "2H" || card == "2D") {
card = 2;
} else if (card == "3C" || card == "3S" || card == "3H" || card == "3D") {
card = 3;
} else if (card == "4C" || card == "4S" || card == "4H" || card == "4D") {
card = 4;
} else if (card == "5C" || card == "5S" || card == "5H" || card == "5D") {
card = 5;
} else if (card == "6C" || card == "6S" || card == "6H" || card == "6D") {
card = 6;
} else if (card == "7C" || card == "7S" || card == "7H" || card == "7D") {
card = 7;
} else if (card == "8C" || card == "8S" || card == "8H" || card == "8D") {
card = 8;
} else if (card == "9C" || card == "9C" || card == "9H" || card == "9D") {
card = 9;
} else {
card = 10;
}
// 4. Update the round score IF the card drawn was NOT a 4 or a 9
if (card !== 2 && card !== 5 && card !== 9) {
// add score
roundScore += card;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
// next player
nextPlayer();
}
// if (card === 5) {
// // add score
// setTimeout(nextPlayer, 2000);
// }
//
// if (card === 9) {
// // add score
// setTimeout(nextPlayer, 2000);
// }
// 5. If deck array runs out, replace all cards in deck ///MAYBE CHANGE THIS SO GAME ENDS AND PLAYER WITH HIGHEST DECK WINS
if (deck.length === 0) {
deck.push("2C", "2S", "2H", "2D", "3C", "3S", "3H", "3D", "4C", "4S", "4H", "4D", "5C", "5S", "5H", "5D", "6C", "6S", "6H", "6D", "7C", "7S", "7H", "7D", "8C", "8S", "8H", "8D", "9C", "9S", "9H", "9D", "10C", "10S", "10H", "10D", "JC", "JS", "JH", "JD", "QC", "QS", "QH", "QD", "KC", "KS", "KH", "KD", "AC", "AS", "AH", "AD");
// deck.push("two-club", "two-spade", "two-heart", "two-dia", "three-club", "three-spade", "three-heart", "three-dia");
shuffleArray(deck);
}
}
}
document.querySelector('.btn-draw').addEventListener('click', function() {
drawCard();
});
function endTurn() {
if (gamePlaying) {
// Add CURRENT score to GLOBAL score
scores[activePlayer] += roundScore;
// Update the UI
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
// Check if player won the game
if (scores[activePlayer] >= 200) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.querySelector('.card').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
// Next Player
nextPlayer();
}
}
}
document.querySelector('.btn-endturn').addEventListener('click', function() {
endTurn();
});
function nextPlayer() {
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.querySelector('.card').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
function init() {
scores = [0, 0];
roundScore = 0;
activePlayer = 0;
gamePlaying = true;
document.querySelector('.card').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
}
#import url('https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght#300;700&display=swap');
.final-score {
position: absolute;
left: 50%;
transform: translateX(-50%);
top: 520px;
color: #555;
font-size: 18px;
font-family: 'Open Sans Condensed', sans-serif;
text-align: center;
padding: 10px;
width: 160px;
text-transform: uppercase;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
background-image: url("img/bg.gif");
background-size: cover;
background-position: center;
font-family: 'Open Sans Condensed', sans-serif;
font-weight: 300;
position: relative;
height: 100vh;
color: #161624;
}
.wrapper {
width: 1000px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #400000;
box-shadow: 0px 10px 50px rgba(0, 0, 0, 1);
overflow: hidden;
color: white;
}
.player-0-panel,
.player-1-panel {
width: 50%;
float: left;
height: 600px;
padding: 100px;
}
/**********************************************
*** PLAYERS
**********************************************/
.player-name {
font-size: 40px;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
font-weight: 100;
margin-top: 20px;
margin-bottom: 10px;
position: relative;
}
.player-score {
text-align: center;
font-size: 80px;
font-weight: 200;
color: white;
margin-bottom: 130px;
}
.active {
background-color: rgb(255, 0, 0, .1);
}
.active .player-name {
font-weight: 700;
}
.active .player-score {
font-weight: 700;
}
.player-current-box {
background-color: #EB4D4D;
color: #fff;
width: 40%;
margin: 0 auto;
padding: 12px;
text-align: center;
}
.player-current-label {
text-transform: uppercase;
margin-bottom: 10px;
font-size: 20px;
color: #fff;
}
.player-current-score {
font-size: 40px;
}
button {
position: absolute;
width: 200px;
left: 50%;
transform: translateX(-50%);
color: #555;
background: none;
border: none;
font-family: 'Open Sans Condensed', sans-serif;
font-size: 30px;
text-transform: uppercase;
cursor: pointer;
font-weight: 300;
transition: background-color 0.3s, color 0.3s;
}
button:hover {
font-weight: 600;
border: 1px solid white;
}
button:focus {
outline: none;
}
/* i {
color: #EB4D4D;
display: inline-block;
margin-right: 15px;
font-size: 32px;
line-height: 1;
vertical-align: text-top;
margin-top: -4px;
transition: margin 0.3s;
} */
.btn-new {
top: 45px;
color: white;
border: 2px solid white;
transition: 0.25s;
}
.btn-draw {
top: 403px;
color: white;
border: 2px solid white;
transition: 0.25s;
}
.btn-endturn {
top: 467px;
color: white;
border: 2px solid white;
transition: 0.25s;
}
.card {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 200px;
}
.back-card {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 200px;
}
.winner {
background-color: #b00000;
}
.winner .player-name {
font-weight: 700;
color: #ff7878;
}
.winner .player-score {
font-weight: 700;
color: #ff7878;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<title>Card Game</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player-score" id="score-0">43</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-0">11</div>
</div>
</div>
<div class="player-1-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player-score" id="score-1">72</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-1">0</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
<button class="btn-draw"><i class="ion-ios-loop"></i>Draw Card</button>
<button class="btn-endturn"><i class="ion-ios-download-outline"></i>End Turn</button>
<img src="img/back-card.png" alt="Back of Card" class="back-card">
<img src="card-5.png" alt="Card" class="card">
</div>
<script src="script.js"></script>
</body>
</html>
I think you already have the answer using setTimeout. But where? Based on your rules I would say you should use on the else, like so:
// 4. Update the round score IF the card drawn was NOT a 4 or a 9
if (card !== 2 && card !== 5 && card !== 9) {
// add score
roundScore += card;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
// next player
setTimeout(() => {
nextPlayer();
}, 2000);
}
But you should freeze the buttons, before you schedule this setTimeout. Because the user would continue playing.
I'd would put something, like so:
freezeButtons();
// next player
setTimeout(() => {
nextPlayer();
}, 2000);
So finally it should work like so:
// 4. Update the round score IF the card drawn was NOT a 4 or a 9
if (card !== 2 && card !== 5 && card !== 9) {
// add score
roundScore += card;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
const buttons = document.querySelectorAll('button');
for(const button of buttons) {
button.disabled = true;
}
// next player
setTimeout(() => {
nextPlayer();
for(const button of buttons) {
button.disabled = false;
}
}, 2000);
}

How do you add a cool down to a button with multiple functions?

There's only one button added, and I want it to - when clicked, have multiple functions
Function 1 returns a "emote" and a GIF.
I want to implement a cooldown so you can't rapidly tap / click the button.
The multiple onClicks isn't working for me either.
I've played around with it and no prevail.
Edit: I changed the way I setup my code,
for some reasion, the two onClick method isn't working, is their an addon for that in Studio Visual Code (currently running it from there)?
<!DOCTYPE html>
<html>
<body>
<style>
.Vibe-Check-heading{
font-size: 50px;
font-family: Comfortaa;
position: absolute;
top: 0px;
left: 765px;
}
.instructions {
font-size: 25px;
font-family: Comfortaa;
position: absolute;
top: 100px;
left: 650px;
}
.steps {
font-size: 15px;
font-family: Comfortaa;
position: absolute;
top: 140px;
left: 650px;
}
.vibe-btn{
font-family: Comfortaa;
padding: .75rem 2.5rem;
font-weight: 600;
background: #424242;
z-index: 10;
color: #fff;
border-radius: 30px;
border: 0;
font-size: 14px;
position: absolute;
top: 200px;
left: 650px;
margin: auto;
width:30%;
size: 40px;
}
#name {
font-family: Comfortaa;
font-size: 25px;
position: absolute;
top: 240px;
left: 680px;
}
#gif {
margin: 20px;
padding: 20px;
position: absolute;
top: 260px;
left: 640px;
}
</style>
<!--------------------------------------------------------------------------->
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Comfortaa" />
<!--------------------------------------------------------------------------->
<div>
<h1 class="Vibe-Check-heading"> Vibe Check</h1>
</div>
<!--------------------------------------------------------------------------->
<div>
<h2 class="instructions"> Instructions: </h2>
<h3 class="steps">click the button. </h3>
</div>
<!--------------------------------------------------------------------------->
<div>
<script>
var adjectives = ["big sad", "vibe check failed","Doot-Doot", "pog","straight-vibin", "bruh moment", "positive","AAAAAAAAAAAA","laundry basket","Jammin"];
var gifs = [
"https://media.tenor.com/images/6eab85d212226d1af8c09bf2103ee955/tenor.gif", //0
"https://i.imgur.com/fBQFAPm.gif", //1
"https://media.giphy.com/media/5MxvgLxp5p732/giphy.gif", //2
"https://pbs.twimg.com/profile_images/630766742336352256/YyIteWQy_400x400.jpg",//3
"https://media.giphy.com/media/gSJfzjAfRUCly/giphy.gif", //4
"https://i.ytimg.com/vi/2ZIpFytCSVc/maxresdefault.jpg", //5
"https://media.giphy.com/media/UqpjszfpiOiLA0L5le/giphy.gif", //6
"https://media.giphy.com/media/WTL02R1L7YCGUEunFy/giphy.gif", //7
"https://p7.hiclipart.com/preview/767/88/925/falkor-the-neverending-story-childlike-empress-meme-laundry-laundry-basket.jpg", //8
"https://i.kym-cdn.com/entries/icons/facebook/000/022/615/CybuEaUVIAAF_HV.jpg" //9
];
function generator(){
var index = Math.floor(Math.random() * adjectives.length);
document.getElementById("name").innerHTML = adjectives[index] + " ";
document.getElementById("gif").src = gifs[index];
alert($("name"));
};
function cooldown() {
var btn = $("vibe-btn");
document.getElementsByClassName("vibe-btn")
btn.css("pointer-events", "none" );
setTimeout(function() {
btn.css("pointer-events", "auto" );
}, 80000);
}
</script>
<button onClick="generator()" class="vibe-btn">The Vibe is</button>
<h1 style="text-align:center" id="name"></h1>
</div>
<!--------------------------------------------------------------------------->
<div>
<img id="gif" width="400" height="400" >
</div>
<!--------------------------------------------------------------------------->
</body>
</html>
You can enable and disable the disable attribute of the button tag
https://www.w3schools.com/jsref/prop_pushbutton_disabled.asp
I used a for loop to set the timer and used booleans to disable and enable the button. Feel free to play around (for some reason I can't get y to change the innerText of the button to alternate between Enabled and Disabled when necessary but that's a different issue for a different post)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button id = "buttonID" type = "button" onclick = "cooldown()" >The Button</button>
<script>
var x = document.getElementById("buttonID").disabled = false;
var y = document.getElementById("buttonID").innerText = "Enabled"
//cooldown function
var cooldown = function(){
//disables or enables the button
var cd = true;
//disables button for a timer
var timer = 0;
for (timer = 0; timer < 9999; timer += 0.5){
if (timer === 9998.5){
cd = false;
} else {
cd = true;
}
console.log(cd)
console.log(timer)
}
//enables and disables buttons depending on value of cd
if (cd === true){
x = document.getElementById("buttonID").disabled = true;
y = document.getElementById("buttonID").innerText = "Disabled"
} else{
x = document.getElementById("buttonID").disabled = false;
y = document.getElementById("buttonID").innerText = "Enabled"
}
}
</script>
</body>
</html>
Instead of disabled, you can use CSS property pointer-events.
var adjectives = ["big sad", "vibe check failed","Doot-Doot", "pog","straight-vibin", "bruh moment", "positive","AAAAAAAAAAAA","laundry basket","Jammin"];
var gifs = [
"https://media.tenor.com/images/6eab85d212226d1af8c09bf2103ee955/tenor.gif", //0
"https://i.imgur.com/fBQFAPm.gif", //1
"https://media.giphy.com/media/5MxvgLxp5p732/giphy.gif", //2
"https://pbs.twimg.com/profile_images/630766742336352256/YyIteWQy_400x400.jpg",//3
"https://media.giphy.com/media/gSJfzjAfRUCly/giphy.gif", //4
"https://i.ytimg.com/vi/2ZIpFytCSVc/maxresdefault.jpg", //5
"https://media.giphy.com/media/UqpjszfpiOiLA0L5le/giphy.gif", //6
"https://media.giphy.com/media/WTL02R1L7YCGUEunFy/giphy.gif", //7
"https://p7.hiclipart.com/preview/767/88/925/falkor-the-neverending-story-childlike-empress-meme-laundry-laundry-basket.jpg", //8
"https://i.kym-cdn.com/entries/icons/facebook/000/022/615/CybuEaUVIAAF_HV.jpg" //9
];
function generator(){
var index = Math.floor(Math.random() * adjectives.length);
document.getElementById("name").innerHTML = adjectives[index] + " ";
document.getElementById("gif").src = gifs[index];
};
function cooldown() {
var btn = $('#vibe-btn');
btn.css("pointer-events", "none" );
setTimeout(function() {
btn.css("pointer-events", "auto" );
}, 15000);
};
.vibe-check-heading{
background-color: rgb(98, 211, 255);
font-size: 20px;
font-family: Comfortaa;
padding: 10rem;
}
#vibe-btn{
font-family: Comfortaa;
padding: .75rem 2.5rem;
font-weight: 600;
background: #424242;
z-index: 10;
color: #fff;
border-radius: 30px;
border: 0;
font-size: 14px;
top: .5rem;
left: .5rem;
margin: auto;
width:50%;
size: 60px;
}
#gif-placer {
margin: 20px;
padding: 20px;
}
.instructions {
font-size: 15px;
font-family: Comfortaa;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Comfortaa" />
<div>
<h1 class="Vibe-Check-heading">
Vibe Check
</h1>
</div>
<div class="instructions">
<h2>
Instructions: <br>
Just click the button.
</h2>
</div>
<div class="vibing">
<button onclick="generator(); cooldown()" id="vibe-btn">The Vibe is</button>
<h1 class="jumbotron text-center rokkitt" id="name"></h1>
</div>
<div class ="gif-placer">
<img id="gif" width="400" height="400" style="border-color: white;" >
</div>

Categories

Resources