I’ve got a problem with a button playing sound files.
There are two buttons, one is enabling the sound-button and the other one plays the sound when clicked. Basically, only buttons with the class “enabled” play sounds, but when I set the class of a button to enabled and then click it, nothing happens.
Working example here
Here is the code:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'http://cd.textfiles.com/10000soundssongs/WAV/DOORBELL.WAV');
$('.enabled').click(function() {
audioElement.play();
});
});
</script>
<script>
$(document).ready(function() {
$('#enabler').click(function() {
$('.disabled').attr('class','enabled');
$('.enabled').text('Play (enabled)');
});
});
</script>
<style>
.enabled{color:green;}
</style>
</head>
<body>
<button class="disabled">Play</button>
<button id="enabler">Make Play-Button work</button>
</body>
</html>
Any help is, as always, much appreciated!
The problem is that when you initiate the
clickevent listener for the.enabledselector, there are no elements with the class ofenabledthat exist to bind the function to. You need to bind the event listener to a parent element that exists so that when the button is clicked it will run the function.You need to change
to
Here is a jsbin showing this.