The idea is that the progress bar should increase when you click the button, for example, if you click on the button play
the happiness
should increase.
const cleanBtn = document.querySelector(".clean"); const feadBtn = document.querySelector(".fead"); const playBtn = document.querySelector(".play"); cleanBtn.addEventListener("click", () => { let health = document.getElementById("myHappines"); health.style.width = 0; if (health.style.width > 100 % ) { health.style.width = 0 % ; else { health.style.width += 10 % ; } } })
<!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>Virtual Pet</title> <!--font-awesome--> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" /> <!--styles--> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="sections-container"> <div class="section1"> <div class="pet-info"> <ul> <div id="basic"> <ul>Name: Elis</ul> <ul>Age: 2 months</ul> </div> <div class="health">Health <div id="myProgressHealth"> <div id="myHealth"></div> </div> </div> <div class="hunger">Hunger <div id="myProgressHunger"> <div id="myHunger"></div> </div> </div> <div class="happiness">Happiness <div id="myProgressHappiness"> <div id="myHappiness"></div> </div> </div> </ul> </div> <button class="btn-settings">Settings</button> </div> <div class="section2"> <div class="pet-interactions"> <ul> <button class="clean">Clean</button> <button class="fead">Fead</button> <button class="play">Play</button> </ul> </div> <div class="game-control"> <li id="name-input">Pet Name <input type="text"></input></li> <li>Game reset button <button class="btn">Reset</button></li> </div> <div class="end-game-message"> <p>Goodbye</p> </div> </div> </div> <!--javascript--> <script src="app.js"></script> </body> </html>
Advertisement
Answer
There are many issues and typos in your code. Clean programming will solve them all.
- You want a bar for which HTML has a specific tag for:
<progress>
. Use it instead ofdiv
s! - Use a
ternary conditional operator
to check if the value is 100 or below and then reset the health bar or add 10% to it:
const cleanBtn = document.querySelector('.clean'); cleanBtn.addEventListener('click', () => { let health = document.getElementById('myHappiness'); health.value = (health.value === health.max) ? 0 : health.value + 10; })
<button class="clean">Clean</button> <br> <label for"myHappyness">Happiness:</label><progress id="myHappiness" value ="0" max="100"></progress>
The main issue with your code where the many typos. Among that was that you used < 100 %
which will divide 100 by an undefined amount and look for the remainder. %
is used as a calculation for a remainder (100 % 3
= 1
) . To use 100%
in the way you intended to, you have to use it as a string.