I am not a programmer! Anyway; I am working on a dictionary app, I need the user to be able to listen to the word when he clicks (or click a small button next to it). Every word is on its own p tag. My approach was to give the p tag an id equal to the word,so for the word apple the p id will be id="apple", and the mp3 file name is "apple.mp3". I need a general script (for the whole page) that grabs the id of the clicked element and push it into an embed inner html function that embeds an audio tag with the src="the clicked id.mp3" and play it. Here what I was trying, but obviously I am missing the correct syntax
<!DOCTYPE html>
<html>
<head>
<title>Get ID of Clicked Element using JavaScript</title>
</head>
<body>
<button id='cat' >cat</button>
<button id='dog' >dog</button>
<script>
document.addEventListener('click', function(e) {
alert(e.target.id);
});
function playSound(soundfile) {
document.getElementById("the grapped Id").innerHTML=
"<embed src= the grapped id""+soundfile+"\" hidden=\"false\" autostart=\"true\" loop=\"false\" />";
}
</script>
</body>
</html>
Some notes:
id use data-* as more suitable attribute for such tasks.Audio() constructor.<!DOCTYPE html>
<html>
<head>
<title>Click a word to listen it</title>
</head>
<body>
<p data-sound="cat">cat</p>
<p data-sound="dog">dog</p>
<script>
var sounds = {};
function loadSound(name) {
if (sounds[name]) {
return sounds[name];
}
var file = '/sounds/' + name + '.mp3',
sound = new Audio(file);
sound.onerror = function() {
alert('File not found: ' + file);
};
sound.onloadedmetadata = function() {
sounds[name] = sound;
};
return sound;
}
function playSound(name) {
var sound = loadSound(name);
if (sound.currentTime > 0) {
sound.pause();
sound.currentTime = 0;
}
sound.play();
}
document.addEventListener('click', function(e) {
if (e.target.dataset && e.target.dataset.sound) {
playSound(e.target.dataset.sound);
}
});
</script>
</body>
</html>