I never really worked with javascript before, but I tried googling for a solution to how to make a play/pause button for audio - and I found what appears to be a good and simple solution on this site: How to toggle audio play() pause() with one button or link? (PS. I don't have reputation poins enough to comment on Iceman's solution and ask him directly what might be wrong - I would have if I could.)
But, when I paste the code snippets into my document, nothing happens (the resulting text isn't clickable). Could some of you take a look and tell me what I'm doing wrong? It's very possible it's something stupid, but I can't see it myself.
Index.html so far:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ukendt Navn ...</title>
<script>
var myAudio = document.getElementById("myAudio");
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
};
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
</script>
<style type="text/css">
#content {
border: 1px solid blue;
margin: auto;
max-width: 20vw;
margin-top: 30vw;
color: black;
}
</style>
</head>
<body>
<div id="content">
<audio id="myAudio" src="birds.mp3" preload="auto"></audio>
<a onClick="togglePlay()">Click here to hear.</a>
</div>
</body>
</html>
My test site: http://wyrdling.com/other/ukendtnavn/
You are trying to call document.getElementById("myAudio")
before the element is loaded, therefore you can either call it after the page fully loaded, or place the script right before the end of body
tag.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ukendt Navn ...</title>
<script>
window.addEventListener('load', function(){
var myAudio = document.getElementById("myAudio");
myAudio.onplaying = function() {
isPlaying = true;
};
myAudio.onpause = function() {
isPlaying = false;
};
});
var isPlaying = false;
function togglePlay() {
if (isPlaying) {
myAudio.pause()
} else {
myAudio.play();
}
}
</script>
<style type="text/css">
#content {
border: 1px solid blue;
margin: auto;
max-width: 20vw;
margin-top: 30vw;
color: black;
}
</style>
</head>
<body>
<div id="content">
<audio id="myAudio" src="http://wyrdling.com/other/ukendtnavn/birds.mp3" preload="auto"></audio>
<a onClick="togglePlay()">Click here to hear.</a>
</div>
</body>
</html>