Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

149
Vistas
Add if statement to a string in JavaScript

I am trying to make an audio file play on my html page (I can get it to play using onclick). But, I am trying to play an audio clip when a specific text is displayed. For instance, I am trying to play an audio clip that needs to be specific to the displayed text (or whatever object).

So, I have some strings (Questions and Answers) but I can't figure out what to assign to the strings to trigger the audio file to play. Also, maybe there's another way by just making a function for each question.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think you want something like this:

  1. Place your audio source as strings in an array, coupled with other info, ( you mentioned questions );
  2. Iterate the array and build the DOM nodes, placing an event listener on click or any other event you want to trigger the sound;
  3. Just add the audio source to the html audio node dinamically when the event occurs and play it;

const data = [{
  question: "What's the name of Culham?",
  choices: ["Alan", "Alastair"],
  answer: "Alastair",
  audio: "https://upload.wikimedia.org/wikipedia/commons/7/7f/Alastair_Culham_voice.ogg"
}, {
  question: "What's the name of Thompson?",
  choices: ["Bill", "John"],
  answer: "Bill",
  audio: "https://upload.wikimedia.org/wikipedia/commons/b/b1/Bill_Thompson_speaking.ogg"
}]


const generate = () => {
  
  root.innerHTML = ""
  audio.src=""
  
  const idx = Math.round(Math.random() * (data.length - 1))
  root.innerHTML += `<div>${data[idx].question}</div>`
  data[idx].choices.forEach(c => {
    const btn = document.createElement("button")
    btn.innerText = c
    btn.onclick = function() {
      if (data[idx].answer === c) {
        audio.src = data[idx].audio
        audio.play()
        audio.onended = generate
      } else alert("Wrong Answer, try again")
    }
    root.appendChild(btn)
  })
}

generate()

reset.onclick = generate
<div id="root"></div>
<audio id="audio"></audio>
<button id="reset">Reset</button>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Don't put your questions in one place and the audio cues in another. Keep them together in data objects that have properties per question. For example:

questions = [
  {
    question: 'What is your quest?',
    answer: 'To seek the holy grail.',
    badAnswers: [
      '16.9 Gigawatts',
      'African or European?',
      'Red. No, blue!'
    ],
    audioQuestion: 'hmm.mp3',
    audioCorrect: 'youtu.be/0D7hFHfLEyk',
    audioIncorrect: 'sproing.mp3'
  },
  {
    question: 'My milkshake brings more boys to the _____.',
    answer: 'yard',
    badAnswers: [
      'stand',
      'steps',
      'park',
      '21st century'
    ],
    audioQuestion: 'hmm.mp3',
    audioCorrect: 'youtu.be/i4YutyVP7ig',
    audioIncorrect: 'sproing.mp3'
  }
]

And then you can have a function that knows what to do when given an element of this array.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda