if(localStorage.getItem("attempts")==1) {
//Show Red color
alert('1')
}
if(localStorage.getItem("attempts")==2) {
//Show Black color
alert('2')
}
if(localStorage.getItem("attempts")==3) {
//Show white color
alert('3')
}
var attempts = Number(localStorage.getItem("attempts"));
localStorage.setItem("attempts", attempts);console.log(attempts);
- I need to show three different color on different visits in circular. for example 1st visit - Red, 2nd visit- Black, 3rd visit- white and again on 4th visit it should start from RED, 5th-WHITE, 6th-BLACK etc..
CodePudding user response:
Maybe something like example below? You will need to adjust it by adding localstorage.
let clicks = 0;
let element = document.getElementById('color');
let btn = document.getElementById('clickbtn');
btn.addEventListener('click', () => {
clicks ;
switch (clicks) {
case 1:
element.style.color = 'red';
break;
case 2:
element.style.color = 'green';
break;
case 3:
element.style.color = 'blue';
break;
}
if (clicks == 3) clicks = 0;
});
<button id="clickbtn">Click</button>
<p id="color">color element</p>
CodePudding user response:
As mentioned in my comment, you have an error in your comparison. You use the single = (a value assignment) instead of == or === a comparison.
In order to cycle through your colors while still counting the requests up, use the modulo operator: %
This calculates the remainder after division. For example 7 % 3
calculates the remainder after dividing 7 by 3 which is 1.
That way you can count up and change the color based on the rest of your division which is always either 0, 1 or 2
let count = 0
window.addEventListener("load", () => {
if (!localStorage.getItem("count")) {
localStorage.setItem("count", count);
} else {
let fetchedCount = parseInt(localStorage.getItem("count"));
fetchedCount ;
localStorage.setItem("count", fetchedCount);
}
});
document.addEventListener("DOMContentLoaded", () => {
let visitingCount = parseInt(localStorage.getItem("count"));
if (visitingCount % 3 === 1) {
document.body.style.backgroundColor = "red";
} else if (visitingCount % 3 === 2) {
document.body.style.backgroundColor = "black";
} else if (visitingCount % 3 == 0) {
document.body.style.backgroundColor = "white";
}
});
CodePudding user response:
let color
window.addEventListener('load', () => {
if (!localStorage.getItem('attempts')) {
localStorage.setItem('attempts', 0)
} else {
let fetchedAttempts = parseInt(localStorage.getItem('attempts'))
fetchedAttempts
localStorage.setItem('attempts', fetchedAttempts)
}
})
document.addEventListener('DOMContentLoaded', () => {
let attemptsCount = parseInt(localStorage.getItem('attempts'))
if (attemptsCount % 3 === 1) {
document.body.style.backgroundColor = 'red'
} else if (attemptsCount % 3 === 2) {
document.body.style.backgroundColor = 'black'
} else if (attemptsCount % 3 == 0) {
document.body.style.backgroundColor = 'white'
}
})