Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
11
rated 0 times [  13] [ 2]  / answers: 1 / hits: 96439  / 10 Years ago, mon, december 8, 2014, 12:00:00

I have an audio file that plays when an anchor tag is clicked. If the anchor tag is clicked again, I want the audio to pause, I just don't know enough about javascript to pull this second half off. I don't want to change the content of the anchor tag they click, I just want the audio file to start and pause whenever they click the tag.



This is what I have so far, which at least makes the sound file playable:



<audio id=audio src=/Demo.mp3></audio>
<a onClick=document.getElementById('audio').play()>Click here to hear.</a>

More From » html

 Answers
9

A Vanilla Javascript way to do what you required.


Note: I've noticed comments on other question with multiple upvotes for a native js approach and saw the OP has no jquery tag.


So WORKING EXAMPLE:


SOLN 1: (my initial soln using events)




var myAudio = document.getElementById(myAudio);
var isPlaying = false;

function togglePlay() {
isPlaying ? myAudio.pause() : myAudio.play();
};

myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};

<audio id=myAudio src=http://www.sousound.com/music/healing/healing_01.mp3 preload=auto>
</audio>
<a onClick=togglePlay()>Click here to hear.</a>




SOLN 2: (using myAudio.paused property based on dandavi's comment)



var myAudio = document.getElementById(myAudio);

function togglePlay() {
return myAudio.paused ? myAudio.play() : myAudio.pause();
};

<audio id=myAudio src=http://www.sousound.com/music/healing/healing_01.mp3 preload=auto>
</audio>
<a onClick=togglePlay()>Click here to hear.</a>




[#68545] Friday, December 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
patienceannel

Total Points: 674
Total Questions: 101
Total Answers: 101

Location: Northern Mariana Islands
Member since Fri, Jan 15, 2021
3 Years ago
patienceannel questions
Fri, Mar 11, 22, 00:00, 2 Years ago
Tue, Oct 20, 20, 00:00, 4 Years ago
Wed, Jul 24, 19, 00:00, 5 Years ago
;