This article is the extension for project 3. Please visit it before starting this for better understanding.
In the last article, we have shown keyboard
and printed clicked letter
in console
. We are going to do following tasks in this article:
Task 1: Speak the clicked letters
Task 2: Print letters just below the keyboard instead in console.
Here is the whole code:
<html>
<body>
</body>
<script>
for (let i = 65; i <= 90; i++) {
const button = document.createElement('button');
const char = String.fromCharCode(i);
const span = document.createElement('span');
span.style.fontSize = '50px';
span.appendChild(document.createTextNode(char));
button.appendChild(span);
document.body.appendChild(button);
button.setAttribute('id', char);
button.style.padding = '30px';
button.style.margin = '10px';
button.onclick = function () { getLetter(char) };
}
function getLetter(id) {
const speech = new SpeechSynthesisUtterance();
const letter = document.getElementById(id).textContent;
speech.text = letter;
window.speechSynthesis.speak(speech);
const p = document.createElement('p');
p.style.fontSize = '30px';
p.innerHTML = letter;
document.body.appendChild(p);
}
</script>
</html>
We have pretty much seen what are we doing inside for
loop in project 3.
We don't need to reinvent the wheel here. Let's jump and understand how we can achieve Task 1 & 2 now.
getLetter
function gets triggered when user clicks on any letter in keyboard.
so, understanding what's inside of it would be suffice.
const speech = new SpeechSynthesisUtterance();
const letter = document.getElementById(id).textContent;
speech.text = letter;
window.speechSynthesis.speak(speech);
The above snippet is responsible for speaking the clicked letter.
SpeechSynthesisUtterance
is the class instantiated in first line. Then, we captured textContent
of the letter clicked. Assign that to speech
to inform synthesisUtterance
which text to speech. After that, use speak
function to speak the word. We are done with Task 1.
Let's move on to Task 2 i.e. printing the clicked item just below the keyboard itself. It's quite straightforward.
const p = document.createElement('p');
p.style.fontSize = '30px';
p.innerHTML = letter;
document.body.appendChild(p);
creating p
element with fontSize
as 30px
for better view. innerHtml
sets letter
to p
and appendChild
appends p
to document body
.
Now, if you click on any letter which will be uttered and displayed on web page.
Here is the result:
Thank You :) Happy Reading!
💎 Love to see your response
- Like - You reached here means. I think, I deserve a like.
- Comment - We can learn together.
- Share - Makes others also find this resource useful.
- Subscribe / Follow - to stay up to date with my daily articles.
- Encourage me - You can buy me a Coffee
Let's discuss further.
- Just DM @urstrulyvishwak
-
Or mention
@urstrulyvishwak
Top comments (0)