Search code examples
jquerymobileswitch-statementtoggleflip

JQM Flip Toggle Switch play stop audio


Im using Flipswitch widget in jQuery Mobile and want to play audio file when the switch is ON and stop when the switch is OFF.

My HTML code:

<audio id="soundtrack">
  <source src="Sounds/soundtheme.ogg" type="audio/ogg">
  <source src="Sounds/soundtheme.mp3" type="audio/mp3">
  Your browser does not support the audio element.
</audio>

    <form>
    <label for="flip-select-audio">AUDIO:</label>
    <select id="flip-select-audio" name="flip-select-audio" data-role="flipswitch">
        <option value="off">OFF</option>
        <option value="on">ON</option>
    </select>
</form>

Im trying to figure out how the JS code could be

$('#flip-select-audio').change(function() {

...

});

Solution

  • You can try something like this :

    $('#flip-select-audio').change(function() {
        var soundtrack = $("#soundtrack")[0];
        if ($(this).val() == "on") {
            soundtrack.play();
        } else {
            soundtrack.pause();
            soundtrack.currentTime = 0;
        }
    
    });
    

    Update : Working perfectly here https://jsfiddle.net/q3Lw8c4g/1/ You should check if your sound file is readable.