Catalina Neshina Catalina Neshina - 5 months ago 11
HTML Question

play sound by click js

I have a problem with playing music. It doesnt play. I want to play music by clicking on the button.

<script>
$(document).ready(function() {
$('.button').submit(function() {
var audio = document.getElementById('audioFile');
audio.play();
});
});
</script>
</head>

<body>
<audio id="audioFile">
<source src="font/sound.mp3" type="audio/mpeg">
</audio>
<div class="inputMessage">

<form method="POST" action="/index.php">
<textarea class="chatMessage" name="text" placeholder="Текст сообщения"></textarea>
<br>
<input class="button" type="submit" name="enter" value="Отправить">
<input type="reset" value="Очистить">
</form>
</div>
</body>

Answer

First thing: .submit() method exists on forms, not inputs. You can use .click() method instead. Second thing: when you click your button the form is sent and page redirects to /index.php. To make playing sound possible you have to stay at the same page (request can still be send asynchronously). Here is the way to prevent loading new page:

$('.button').click(function(ev) { // jQuery passes the event as a parameter
  var audio = document.getElementById('audioFile');
  audio.play();
  ev.preventDefault(); // and we prevent the form from being sent
});

Take a look at demo: https://jsfiddle.net/s48jcrvc/1/