Search code examples
javascriptjqueryhtmlspeech-synthesis

how to make a button to read the text of div


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.


Solution

  • With jQuery it's very simple:

    $(document).ready(function(){
        $('.btn').click(function(){
            alert($(this).prev().text());
        });
    });
    

    DEMO: https://jsfiddle.net/u4wmt9Lf/

    Note: I also change the repeated ids to classes.

    EDIT:

    Try this pure JavaScript version, it should work for you:

    var buttons = document.getElementsByClassName('btn');
    for(var i = 0, len = buttons.length; i < len; i++) {
        buttons[i].onclick = function (e) {
            var prev = e.target.previousElementSibling;
            var text = prev.innerText || prev.textContent;
            alert(text);
        }
    }
    

    DEMO: https://jsfiddle.net/lmgonzalves/u4wmt9Lf/11/