Reputation: 63
I am making a mental health website in which there is a meditation area. there are two div cards and inside of each, there is one button that plays and stops music when clicked.
I am using script tags inside the html file for extra information.
Purpose: when the buttons inside each of the two card div is clicked, a guided meditation audio should play. there is a long audio and a short audio that comes in two formats of mp3 and ogg.
Problem: one of the audios play perfectly but the second one doesn't work. meaning it wont play and stop when the button is clicked. can you please check and tell me what's wrong.
<div class="main-box">
<div class="slot1">
<p class="line line1">this is the long music</p>
<audio id=rollSound loop>
<source src="sounds/long-medi.mp3" type="audio/mpeg">
<source src="sounds/long-medi.ogg" type="audio/ogg">
Your browser does not support the sound files. Please proceed by using other solutions.
<!--the obove text will only show if the users' browser does not play the two files. -->
</audio>
<button id=play>play/stop</button>
<script>
const rollSound = document.getElementById('rollSound');
const btn = document.getElementById('play');
btn.addEventListener("click", e => rollSound.paused ? rollSound.play() : rollSound.pause());
</script>
</div>
<div class="slot2">
<p class="line line2">this is for short music</p>
<audio id=shortsound loop>
<source src="sounds/short-medi.mp3" type="audio/mpeg">
<source src="sounds/short-medi.ogg" type="audio/ogg">
Your browser does not support the sound files. Please proceed by using other solutions.
</audio>
<button id=roll>play/stop</button>
<script>
const shortsound = document.getElementById('shortsound');
const btn = document.getElementById('roll');
btn.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
</script>
</div>
Upvotes: 0
Views: 133
Reputation: 487
There is an error when executing your script because you can not declare var btn =
a second time.
Instead change the following
const shortsound = document.getElementById('shortsound');
const btn = document.getElementById('roll');
btn.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
to something like this:
const shortsound = document.getElementById('shortsound');
const btn2 = document.getElementById('roll');
btn2.addEventListener("click", e => shortsound.paused ? shortsound.play() : shortsound.pause());
and it will work, see this jsfiddle:
https://jsfiddle.net/snw3950L/1/
Upvotes: 1