Small problem, with my Javascript code the program is suppose to read with getElementById
, but I cannot get this to work with my main
and <p>
tags the program will only read with an input
tag (I want to program to read the text on the website).
The program will only say “Undefined” whenever I press the button.
Does anyone know the idea for this issue.
Area in code where Text-To-Speech won’t work
<main id="text"> This program API is not working </main> <p id="text"> This is also not read </p>
The Supporting button
<button type="button" onclick="SoeechModule()" class="btn btn-info" "> Text To Speech </button>
The Javascript which works (Other than the aforementioned issue)
function SpeechModule(var1) { const TxtToSpeech = new SpeechSynthesisUtterance(); let voices = speechSynthesis.getVoices(); let search = document.getElementById("data").innerHTML; TxtToSpeech.text = search; TxtToSpeech.volume = 2; TxtToSpeech.rate = 0.5; TxtToSpeech.pitch = 2; TxtToSpeech.voice = voices[4]; window.speechSynthesis.speak(TxtToSpeech); }
Advertisement
Answer
You need to use innerText for each element. Also you are using id="text"
multiple times, id is unique and you can fetch only the first item with it if you assign same id to multiple elements. Run the updates code snippet:
function TextToSpeech() { const speech = new SpeechSynthesisUtterance(); let voices = speechSynthesis.getVoices(); //let convert = document.getElementById("text").value; speech.text = document.getElementById("text1").innerText; window.speechSynthesis.speak(speech); speech.text = document.getElementById("text2").innerText; window.speechSynthesis.speak(speech); }
<main id="text1"> This program API is not working </main> <p id="text2"> This is also not read </p> <button type="button" onclick="TextToSpeech()" class="btn btn-info" "> Text To Speech </button>