skip to Main Content

I am building a webpage with the spanish alphabet framed in a grid and I want the user to hear how the letters sound whenever they click on them.

There are 27 divs (for each letter) and 27 variables (each are assigned an audio file) therefore I want to connect them somehow.

This is the HTML code (part of it):

  <div class="grid-item" id="a">A</div>
  <div class="grid-item" id="b">B</div>
  <div class="grid-item" id="c">C</div>
  <div class="grid-item" id="d">D</div>

This is the JS code (part of it):

   const a = new Audio('a.mp3');
   const b = new Audio('b.mp3');
   const c = new Audio('c.mp3');
   const d = new Audio('d.mp3');

How can I build a function that will enable the user to hear the audio file when they click on the div?

I tried to build an array of the variables then loop them along with the ID’s but it failed.

2

Answers


  1. You can create an array of the audio variables and assign a click event listener to each div element in the grid:

    const alphabetAudios = {
      a: new Audio('a.mp3'),
      b: new Audio('b.mp3'),
      c: new Audio('c.mp3'),
      d: new Audio('d.mp3'),
      // Add the rest of the audio variables here
    };
    
    // Add click event listener to each div element in the grid
    const divs = document.getElementsByClassName('grid-item');
    for (let i = 0; i < divs.length; i++) {
      divs[i].addEventListener('click', playAudio);
    }
    
    function playAudio(event) {
      const divId = event.target.id;
      const audio = alphabetAudios[divId];
      
      // Check if audio exists for the clicked div
      if (audio) {
        audio.play();
      }
    }
    

    JSFiddle with sample audio.

    Login or Signup to reply.
  2. Thanks for the question. I have an option here that uses onclick to reference a javascript object to select and play a sound based on the div’s id.

    HTML:

    <div class="grid-item" id="a" onclick="playAudio(this.id)">A</div>
    <div class="grid-item" id="b" onclick="playAudio(this.id)">B</div>
    <div class="grid-item" id="c" onclick="playAudio(this.id)">C</div>
    <div class="grid-item" id="d" onclick="playAudio(this.id)">D</div>
    

    JS:

    const audioFiles = {
        a: new Audio('a.mp3'),
        b: new Audio('b.mp3'),
        c: new Audio('c.mp3'),
        d: new Audio('d.mp3')
    };
      
    function playAudio(event) {
        const audio = audioFiles[event];
        if (audio) {
          audio.play();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search