i want to add new function after i clicked the button 3 times and erase/remove the former function
html file:
JavaScript
x
7
1
<body>
2
<div id="background">
3
<p>this background white, before</p>
4
</div>
5
<button class="btn-1">change color</button>
6
</body>
7
javascript:
JavaScript
1
12
12
1
const btn1 = document.querySelector(".btn-1") ;
2
const bg = document.getElementById("background")
3
4
const toRed = ()=>{
5
bg.style.backgroundColor = "red";
6
}
7
const toBlue = ()=>{
8
bg.style.backgroundColor = "steelblue";
9
}
10
11
btn1.addEventListener('click', toRed);
12
// i want this btn1 have function to clear function toRed and add toBlue instead after clicked 3 times
Advertisement
Answer
remove the event listener and add a new one when it was clicked three times:
JavaScript
1
16
16
1
const btn1 = document.querySelector(".btn-1");
2
const bg = document.getElementById("background");
3
var redClicked = 0;
4
const toRed = ()=>{
5
bg.style.backgroundColor = "red";
6
redClicked++;
7
if (redClicked >= 3) {
8
btn1.removeEventListener('click', toRed);
9
btn1.addEventListener('click', toBlue);
10
}
11
}
12
const toBlue = ()=>{
13
bg.style.backgroundColor = "steelblue";
14
}
15
16
btn1.addEventListener('click', toRed);
JavaScript
1
6
1
<body>
2
<div id="background">
3
<p>this background white, before</p>
4
</div>
5
<button class="btn-1">change color</button>
6
</body>