Reputation: 3
I have a single link and I want the link to play different sounds each time it is clicked. When I click the link it plays both sounds at the same time but I want one sound at a time
var bleep = new Audio('hello.mp3') ;
bleep.src = "hello.mp3" ;
var bleep2 = new Audio('goodbye.mp3') ;
bleep2.src = "goodbye.mp3";
<a href="#" onclick="bleep.play('hello.mp3'); bleep2.play('goodbye.mp3');">Home</a>
Upvotes: 0
Views: 557
Reputation: 1305
You should make a function out of it that checks which sound was clicked last time. Also, you neither need to set the .src
property or pass a string to the play method.
JS:
var bleep = new Audio('hello.mp3');
var bleep2 = new Audio('goodbye.mp3');
var playFirst = true;
function playSound() {
if (playFirst) {
bleep.play();
} else {
bleep2.play();
}
playFirst = !playFirst;
}
HTML:
<a href="#" onclick="playSound()">Home</a>
Upvotes: 2
Reputation: 727
Instead of attaching the event listener inline as onclick
, attach it with JS using addEventListener
. This allows you to pick which audio clip to play:
var helloSound = new Audio('hello.mp3');
helloSound.src = "hello.mp3";
var goodbyeSound = new Audio('goodbye.mp3');
goodbyeSound.src = "goodbye.mp3";
var homeLink = document.getElementById('home-link');
homeLink.addEventListener('click', function () {
if (/* condition to play hello */) {
helloSound.play();
} else {
goodbyeSound.play();
}
});
Markup:
<a href="#" id="home-link">Home</a>
Upvotes: 2