Mina
Mina

Reputation: 315

Play a specific audio based on hovered image (javascript)

I'm supposed to have 5 animal images on the site, and whenever I hover over an animal, their characteristic sound plays. Is there a more efficient way to do this rather than using switch case? This is what I have so far (works only for 1 animal):

HTML:

<img src="img/piggy.png" onmouseover="F1(this)">

JS:

function F1(img) { 
var audio = document.getElementById("audio");
audio.play();
}

Upvotes: 2

Views: 81

Answers (2)

Mouradif
Mouradif

Reputation: 2704

You can have the sound to play embedded in the img tag's dataset :

<img src="img/piggy.png" data-sound='piggy.wav' onmouseover="playSound(this)">
function playSound(element) { 
  var audio = new Audio(element.dataset.sound);
  audio.play();
}

you may want to pre-load all of the audio files on page load

Upvotes: 1

Calvin Bonner
Calvin Bonner

Reputation: 580

I think this is a really solid base. If it were me I would do almost exactly what you are doing but set up an array with the list of available sound bites. Then, onmouseover pass in a number (0-5) and use that as the selector to choose which soundbyte plays.

var sounds = ["sound1", "sound2", "sound3", "sound4", "sound5"];

function playAudio(track) {
   audio.play(sounds[track]);
}

Hopefully that's clear/helpful. Otherwise, let me know and I'll be glad to clarify.

Upvotes: 1

Related Questions