how to make a button to read the text of div

1.4k views Asked by At

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.

2

There are 2 answers

3
lmgonzalves On BEST ANSWER

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/

4
Vel On
$(document).ready(function(){
    $('.btn').click(function(){
            speechSynthesis.cancel()    ;
      var text_to_read = $(this).prev().text();
        var u = new SpeechSynthesisUtterance(text_to_read);
   speechSynthesis.speak(u); if(!/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())){
     u.rate = .2;
    }
    u.text = text_to_read.textContent;

    });

});


<div id="text1">Lorem ipsum</div>
<button class="btn">Speak</button>
<div id="text2">This is the second block</div>
<button class="btn">Speak</button>

try this

UPDATED