cindyg cindyg - 6 months ago 22
HTML Question

how to stop sound playing when I'm not clicking on the image?

I want to play sound when I click on the image (which I put as a background image in a div), and not playing the sound when my mouse is up.So the sound will only play when mouse is down. But right now, the sound won't stop playing after one-click on the image.

Here is my html for the div:

audio id="audio" src="sound/sound1.mp3" preload="auto"

class="container1" onclick="play()" value="PLAY"

Here is my JavaScript:

function play(){

var audio = document.getElementById('audio');
audio.currentTime = 0;;


Maybe I should make another function called pause() and use onmouseup="pause()" in HTML? But how to do another function to call this one to stop? I'd love to hear some suggestions. I'm a newbie here. Sorry about the formatting. Thanks!


use onmousedown and onmouseup events instead of onclick. Add method for pausing audio.

function pause(){
  var audio = document.getElementById('audio')

after that in your html add events onmousedown="play()" onmouseup="pause()". That should work.