SandStone
SandStone

Reputation: 358

Add text to speech to every text node to website built with React

The user can activate to TTS from a button then when they hover on an text, the text should be uttered. Example is this website here https://www.monshaat.gov.sa/en
-> You activate the text to speech from the button

You activate the tts from the button

-> Whenever you hover on an element it background color changes and the text is uttered tts

Any ideas of clean ways I can implement this to a big react project.

Upvotes: 1

Views: 785

Answers (1)

Chong Lip Phang
Chong Lip Phang

Reputation: 9279

Take a look at the Speech Synthesis Web API:

https://www.webcodingcenter.com/web-apis/Web-Speech-APIs

Something like this:

var t = document.getElementsByClassName('readOut');
for (let i = 0; i < t.length; i++) {
   t[i].addEventListener('mouseover', readout_handler);
}

function readout_handler(e){
    let text = e.target.textContent;
    //...
}

If you use React, you can just create a generic ReadOut element, then implement the mouseover event directly, like this:

function ReadOut(props){
    return <p onMouseOver={()=>readout_handler(props.children)}}>{props.children}</p>;
}

Then just include it in your React app everywhere:

<ReadOut>Hello there!</ReadOut>

I have not tested all the codes above, but it should not be far from the right answer.

Upvotes: 2

Related Questions