I wanted to create a play/pause button on my webpage that flips between play/pause when clicked. I used the on function to create a click event to trigger the song play and pausing. However, the first click does everything as expected, preventing the default action of refreshing the page, but when clicking the same button after it's been switched to a pause button, it does not prevent the default action. I have tried using preventDefault() for both of them and even stopPropagation() and return false, which still doesn't work. I am assuming this has to do with something with using replaceWith() and possibly removing events or something but I am not sure how all of this works.
I have also tried repurposing this for other functions like a mute button and having the pause play first with everything working fine on the first click but not the second.
play = $('#play');
pause = $('#pause');
play.on('click', function(e) {
e.preventDefault();
song.play();
$(this).replaceWith('<a class="button" id="pause" href="" title=""></a>');
container.addClass('containerLarge');
cover.addClass('coverLarge');
});
pause.on('click', function(e) {
e.preventDefault();
song.pause();
$(this).replaceWith('<a class="button" id="play" href="" title=""></a>');
});