Catalina Neshina Catalina Neshina - 1 year ago 84
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.

$(document).ready(function() {
$('.button').submit(function() {
var audio = document.getElementById('audioFile');;

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

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

Answer Source

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');;
  ev.preventDefault(); // and we prevent the form from being sent

Take a look at demo:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download