0 votes
asked Jun 11 by alebot (160 points)


I am using a click-to-play code that plays my background audio so it works in web browser. This music works as background music and plays until it times out. Though, I would like a code that will allow me to click a "game over" hypertext that stops the music. 

My current javascript is: 

$(document).on('click', '.audio', function () {
    new Audio('').play();

Inside the passage, I am using: 

[[<span class='audio'>PRESS START ▼</span>|1]]

I know there's probably an easy solution...just don't know what it is yet. Thanks for all your help!!

1 Answer

0 votes
answered Jun 11 by Chapel (46,530 points)

You'll need to cache a reference to that Audio instance so you can do more stuff to it. For example: 

var song = new Audio(...);

$(document).on('click', '.audio tw-link', function () {;

$(document).on('click', '.audio-stop tw-link', function () {
    song.currentTime = 0;

You'll notice that I changed the selectors to '.class tw-link'. So you'd move your spans out of the link markup to use this, which is safer than putting them inside the markup: 

<span class='audio'>[[link]]</span>

Also, I have heard that creating an actual <audio> element (with jQuery, probably) rather than using the Audio constructor is better, but someone more knowledgeable than me would probably know more about that.