I'm trying to make it so that an image can be clicked 3 times before it disappears, and I would like that function to repeat itself. At this point it only works the first time the image pops up, after that it disappears after 1 click. Sorry for the confusing code.(It works now)
let clickMonster3=0;
const monsterCounter3=()=>clickMonster3 ;
function monster003(){
if(clickMonster3==3){
this.style.display='none'
}else{
monsterCounter3()
}
wolfmonster3.onclick=monster003;
setInterval(monster003,6000);
CodePudding user response:
keep on each image an attribute that denotes it's click count. increase it on every click and if it's 3 then set the image to be display:none;
you should setInterval(monster003,6000) only once
function newMonster() {
var img = new Image();
img.src = "https://picsum.photos/100";
img.setAttribute("data-click-count", 0);
img.onclick = function() {
var current = this.getAttribute("data-click-count") 1
this.setAttribute("data-click-count", current);
if (current == 3) {
this.style.display = 'none'
}
}
document.body.append(img)
}
setInterval(newMonster, 3000);
newMonster();
CodePudding user response:
Change
setInterval(monster003,6000);
into
setInterval(() => {
clickMonster3 = 0;
monster003();
}, 6000);
You need to reset your counter variable - in this case as I see it is called clickMonster3
- back to 0 so it can be counted 3 times.
Word of advice: call your variables and methods with some sense, and write your code more tidy, with insets, no extra spaces or rows etc.
CodePudding user response:
Save click count in a data-attribute
on the image. Use setTimeout
within the handler instead of setInterval
. The snippet uses event delegation to handle the initial click.
document.addEventListener(`click`, handle);
function handle(evt) {
if (evt.target.dataset.clickcount) {
console.clear();
evt.target.dataset.clickcount = evt.target.dataset.clickcount 1;
if ( evt.target.dataset.clickcount < 3) {
console.log(`${evt.target.dataset.img} clicked ${
evt.target.dataset.clickcount} time(s), hiding 2 seconds`);
evt.target.classList.add(`hide`);
return setTimeout(_ => evt.target.classList.remove(`hide`), 2000);
}
console.log(`${evt.target.dataset.img} clicked ${
evt.target.dataset.clickcount} times, hiding permanently`);
return evt.target.style.display = `none`;
}
}
img {
width: auto;
height: 100px;
opacity: 1;
transition: opacity 1s 0s;
}
img.hide {
opacity: 0;
}
<img src="//cdn.pixabay.com/photo/2012/05/02/17/24/ground-45742_960_720.png"
data-clickcount="0" data-img="img1">
<img src="//cdn.pixabay.com/photo/2015/04/23/22/01/mountains-736886_960_720.jpg"
data-clickcount="0" data-img="img2">