I now have a div with a circle that, when clicked, will animate and turn on the sound.
The question is, can I make the sound play not every click, but let’s say every 10 clicks, or randomly from 1 to 10 clicks?
Should I do this condition in the click function itself?
var clickEl = document.getElementById("clicks");
let clicks = 0;
let listDiv = document.querySelectorAll("div");
A = document.createElement('audio');
A.src = 'http://www.freesound.org/data/previews/265/265296_5003039-lq.mp3'; A.volume=0.3;
for (let div of listDiv) {
div.addEventListener('click', () => {
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => {
div.style.animation = '';
}, 220);
clickEl.innerText = ++clicks;
A.currentTime=0.09; A.play();
});
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
border: 3px solid red;
margin: 20px;
}
@keyframes Animation {
0% {
transform: scale(1);
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
}
}
<div class="circle animation"></div>
<span>Clicks: <a id="clicks">0</a></span>
>Solution :
I implemented that logic in this sandbox
You can give it a try
Here is the full implementation with some explanation
var clickEl = document.getElementById("clicks");
let clicks = 0;
let previousPlayClickCount = 0; //keep the previous click count for finding the next play
let nextPlay = Math.floor(Math.random() * 10); //set next play from 0 to 9
let listDiv = document.querySelectorAll("div");
A = document.createElement('audio');
A.src = 'http://www.freesound.org/data/previews/265/265296_5003039-lq.mp3';
A.volume = 0.3;
for (let div of listDiv) {
div.addEventListener('click', () => {
clickEl.innerText = ++clicks;
//don't trigger sound after certain clicks (with random count `nextPlay`)
if (previousPlayClickCount + nextPlay !== clicks - 1) {
return
}
//need to track previous click count and randomize next play again
previousPlayClickCount = clicks;
nextPlay = Math.floor(Math.random() * 10);
div.style.animation = 'Animation 200ms linear forwards';
setTimeout(() => {
div.style.animation = '';
}, 220);
A.currentTime = 0.09;
A.play();
});
}
.circle {
width: 80px;
height: 80px;
border-radius: 80px;
border: 3px solid red;
margin: 20px;
}
@keyframes Animation {
0% {
transform: scale(1);
}
50% {
transform: scale(.8);
}
100% {
transform: scale(1);
}
}
<div class="circle animation"></div>
<span>Clicks: <a id="clicks">0</a></span>
The debugged values in this screenshot
if clicks = nextPlay + previousPlayClickCount, the sound will be triggered. After that, nextPlay and previousPlayClickCount will be reset
