I'm trying to make a button "Speak" that should basically read the text content of the previous div.
So for instance I have:
<div id="text1">Lorem ipsum</div>
<button id="btn">Speak</button>
<div id="text2">This is the second block</div>
<button id="btn">Speak</button>
and use such javascript code
<script type="text/javascript">
var btn = document.getElementById('btn');
speechSynthesis.cancel()
var u = new SpeechSynthesisUtterance();
var text_to_read = document.getElementById('step1');
jQuery.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
if(!jQuery.browser.chrome){
u.rate = .2;
}
u.text = text_to_read.textContent;
btn.onclick = function () {speechSynthesis.speak(u);};
</script>
Now, instead of use "step1" in this line: var text_to_read = document.getElementById('step1'); I need to retrieve the text on the div immediately before the button.
Hope it is clear enough.
Sorry I'm not a JS coder.
With jQuery it's very simple:
DEMO: https://jsfiddle.net/u4wmt9Lf/
Note: I also change the repeated
ids
toclasses
.EDIT:
Try this pure JavaScript version, it should work for you:
DEMO: https://jsfiddle.net/lmgonzalves/u4wmt9Lf/11/