Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda