ThePlacid ThePlacid - 2 months ago 7x
Javascript Question

Play an audio file on hover

I have made this script for my forum and I was wondering if anyone could guide me how to get the browser to play an audio file if the user hovers over the class

, but it has to give them a warning alert that says
"audio is about to play"
if they press ok on the alert it should play if they press cancel it should not. How can I achieve this? Here is the script I have so far:

my script has been removed


You can use the following code:

var elems = document.getElementsByClassName("style113");
for(i in elems) {
    elems[i].addEventListener("mouseover", function() {
        if(confirm(" %%% CONFIRMATION MESSAGE %%% ")) {
            // %%% CODE TO PLAY SOUND %%%

What it does:

  1. Loops over elements of class style113
  2. Adds an event listener to each element to event mouseover
  3. In each event listener, creates a confirm() popup (has two buttons, one to confirm and one to cancel)
  4. If the confirm() method returns true (if the positive button is clicked), then play sound

Working example on JSFiddle

UPDATE As per OP request in the comments below, you can add this code to your specific code in the for loop:

document.getElementsByClassName('style113')[x].addEventListener("mouseover", function() {
    if(confirm("audio is about to play")) {
        // %%% CODE TO PLAY SOUND %%%

I'd also advise you to clean up your source code with better indenting practices. Also, avoid making too many DOM requests (e.g., repetitive document.getElementsByClassName()) and look instead to caching DOM requests.