Hyperlinks shouldn't be used as "hooks" for click events in the first place. Hyperlinks are for navigation and to use them for other purposes can cause problems for those who rely on assistive technologies to interact with the page.
In your case, when you click the link, you have two things happening, first the native navigation to the href
and second the click
event handler, which is often a "conflict of interests" of sorts.
Just about every element that you can see on a page supports a click
event and so an element like a span
should really be used here. A span
or a div
are semantically neutral - - they don't convey any particular meaning for the data they contain, so they are great for custom non-semantical data like you need here.
You've also got an issue with the way you've created the audio
element - - you never actually included it into the DOM, so it's never visible.
Really, you just need to use the HTML5 native audio
element that starts out as part of the DOM, just hidden. Then, with a click to a span
you simply unhide the element (which has already been configured to show its controls) and instruct it to play the audio.
Also, you should not be setting events up using HTML event attributes. That is a 25+ year old technique that we used before we had standards. Instead, do your event wiring in JavaScript with .addEventListener()
as seen below.
const player = document.querySelector("audio");
document.querySelector("#audio").addEventListener("click", function(){
player.classList.remove("hidden");
player.play();
});
.hidden { display:none; }
/* Make the span look and feel like a clickable element */
#audio { cursor:pointer; color:blue; }
#audio:hover { color:red; }
<span id="audio">Play Audio</span>
<audio controls src="https://www.learningcontainer.com/wp-content/uploads/2020/02/Kalimba.mp3" class="hidden"></audio>
Also, is there a way to make the audio persist so that it will
continue playing while the visitor navigates to other pages within the
site?
No. Most browsers will stop playing media when the browser tab loses focus and, in the case of navigating to another page in the site, the first page would be unloaded and so the audio
element would no longer exist. If you really want this capability, you should look into having a SPA (single page application) and you could load new content via AJAX calls or using an iframe
. This would allow you to never leave the page and therefore the audio would keep playing.