Reputation: 31
I have this code and just play, but I want to play and pause with the same button (image) and I don't know what I need to add, what I need to do? Help me please
<script>
function play(){
var audio = document.getElementById("audio");
audio.play();
}
</script>
<input type="image" id= "Portada1" src= "https://66.media.tumblr.com/dc48784826909289a58767fed35ba421/tumblr_pu7p4w8Jai1yrcbyio1_1280.jpg" alt ="Portada del sencillo Tim McGraw de Taylor Swift." onclick="audio.play ()">
<audio id="audio" src="Audio/Teardrops On My Guitar.mp3" ></audio>
</body>
Upvotes: 2
Views: 834
Reputation: 43880
<input type='image'>
are actually fancy submit buttons which full functionality is possible when nested within a <form>
, but for OP's purposes, a <button>
with a background-image
is not only semantically accurate but also ensures there will be no possible side-effects.
<button type='button'></button>
button { background: url(https://example.com/path/to/image.jpg)....}
To toggle .play()
and .pause()
methods on an audio object, either use
if (audio.paused || audio.ended) {... //if audio is not playing
OR
if (audio.playing) {... // if audio is playing
document.querySelector('button').onclick = player;
function player(event) {
const clicked = event.target;
clicked.classList.toggle('playing');
const song = document.querySelector('audio');
if (song.paused || song.ended) {
song.play();
} else {
song.pause();
}
}
button {
background: url(https://www.hardwoodandhollywood.com/pop-culture-spin/wp-content/uploads/sites/7/2015/02/florencemachine.jpg)no-repeat;
background-size: contain;
display: inline-block;
width: 124px;
height: 86px;
cursor: pointer;
border: 3px solid rgba(158, 127, 103, 0.7);
box-shadow: 4px 6px 7px rgba(158, 127, 103, 0.6);
border-radius: 20%;
}
button:hover {
border: 3px solid rgba(158, 127, 103, 1);
}
.playing {
border: 3px solid rgba(58, 127, 203, 0.7);
box-shadow: 4px 6px 7px rgba(58, 127, 203, 0.6);
}
.playing:hover {
border: 3px solid rgba(58, 127, 203, 1);
}
button:focus {
outline: 0
}
<button type='button'></button>
<audio src='https://gldrv.s3.amazonaws.com/av/Florence_and_the_Machine-Dog_%20Days_are_Over.mp3'></audio>
Upvotes: 1
Reputation:
// on top of your JS file
let isPlaying = false;
// your function
function play() {
var audio = document.getElementById("audio");
if (isPlaying) {
audio.play();
} else {
audio.stop();
}
isPlaying = !isPlaying;
}
Upvotes: 1