Help me writing the Javascript Please!!
I want to make a streak just like the snapchat streaks when you click yes button and the streaks will be broken when the cross/reset/no button is pressed!
But here comes the Main thing that i want every users streak to be stored in their account ,for which i'll add Authentication on the Project Later!
I'm using MongoDB for storing Users and Streaks
The Streaks will be Displayed here:
<p >
Praying without any Break since
<span id="streaks">0</span> day(s)!
</p>
These are the Buttons:
<div >
<h1 >Have you offered all Prayers Today?</h1>
<div >
<!-- YES Button -->
<button
id="answer_yes"
onclick="updateScores"
>
<span>✓</span>
</button>
<!--NO BUtton-->
<button
id="answer_no"
>
<span>✗</span>
</button>
</div>
</div>
THe Javascript i was trying was this:
const yes = {
score: 0,
button: document.querySelector("#answer_yes"),
display: document.querySelector("#streaks"),
};
const resetButton = {
score: 0,
button: document.querySelector("#answer_no"),
display: document.querySelector("#streaks"),
};
function updateScores(streaks) {
streaks.score = 1;
streaks.display.classList.add("has-text-success");
streaks.button.disabled = true;
streaks.display.textContent = streaks.score;
}
yes.button.addEventListener("click", function () {
updateScores(streaks);
});
resetButton.addEventListener("click", reset);
function reset() {
for (let p of [yes, resetButton]) {
p.score = 0;
p.display.textContent = 0;
p.button.disabled = false;
}
}
P.S: I'm a Beginner so bear with my useless and shitty Code! This my First Full-Stack Project and i can't even create the Javascript.
CodePudding user response:
I saw that your current code is all basic HTML and JavaScript and it is not working. So I made it work.
After changing, this is your HTML code:
<p >
Praying without any Break since
<input id="streaks" value=0 disabled/> day(s)!
</p>
<div >
<h1 >Have you offered all Prayers Today?</h1>
<div >
<button
id="answer_yes"
onclick="onYesButton()"
>
<span>✓</span>
</button>
<button
id="answer_no"
onclick="onNoButton()"
>
<span>✗</span>
</button>
</div>
</div>
And this is your JS code:
function onYesButton() {
if ( document.getElementById('streaks').value >= 0) {
document.getElementById('streaks').value =
document.getElementById('streaks').value 1;
}
}
function onNoButton() {
if ( document.getElementById('streaks').value >= 1) {
document.getElementById('streaks').value =
document.getElementById('streaks').value - 1;
}
}
You can check it now, the functionality works as you wanted.