0

I'm trying to use jQuery to add class "active" to a link when clicked, then auto-remove after 6 seconds. If link has class "active" when clicked, then go ahead and remove class. I am also trying to this link to play/stop play of mp3.

HTML:

<audio id="cat-growl-sound" controls>
  <source src="sound.mp3" type="audio/mpeg">
</audio>


<a id="cat-growl-link" href="javascript:void(0)">Fire Me!</a>

CSS:

audio { display: none; }
#cat-growl-link.active { color: red; }

JQUERY:

$('#cat-growl-link').click(function() {
  $("#cat-growl-sound")[0].play();
  $(this).addClass('active');
  $(this).removeClass('active').delay(6000);
});
$('#cat-growl-link.active').click(function() {
  $("#cat-growl-sound").stop();
  $(this).removeClass('active');
});

I have tried different methods to try to get this working, but the different methods only get parts of it working, not all of it. This script I chose to post here I think best explains what I am attempting to do, even though it doesn't work. How do I get this working properly?

Here is a jsFiddle with working sound: https://jsfiddle.net/tcmpguok/

Xarcell
  • 2,011
  • 6
  • 33
  • 65

1 Answers1

1

A couple of problems. Firstly, delay() works only on jQuery methods that use the animation queue - in other words, asynchronous operations. Even then, only methods chained after delay() will be delayed, not those before it.

Secondly, your second event handler isn't dynamic; it'll bind to any element that matches #cat-growl-link.active at the time the page loads - not in the future, as the element's class is added/removed.

All in all, you probably want something like this:

let audio = $("#cat-growl-sound")[0],
    timeout;
$('#cat-growl-link').on('click', function() {
    if (!$(this).is('.active')) {
        $(this).addClass('active');
        audio.play();
        timeout = setTimeout(() => $(this).removeClass('active'), 6000);
    } else {
        $(this).removeClass('active');
        clearTimeout(timeout);
        audio.pause();
        audio.currentTime = 0;
    }
});
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • Thank you for taking the time to explain. One problem with the snippet though, I get an console error: "audio.stop is not a function.". – Xarcell Dec 10 '20 at 19:35
  • I tried replacing " audio.stop" with the accepted answer from this question(https://stackoverflow.com/questions/14834520/html5-audio-stop-function), but that didn't work either. – Xarcell Dec 10 '20 at 19:39
  • replace `audio.stop` with `audio.pause(); audio.currentTime = 0;`, and I'll accept it as the correct answer. – Xarcell Dec 10 '20 at 19:44