I want to build this keyboard phase by phase as we regularly do. Today[25-FEB-2021], I am going to build basic keyboard implementation.
Task 1: Show all alphabets on web page.
Task 2: Print the letter in browser console on click.
Here is the 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 letter = document.getElementById(id).textContent;
console.log(letter);
}
</script>
</html>
Task1:
for (let i = 65; i <= 90; i++) {
-> 65 - 90 ASCII values for alphabets. Loop iterates between 65-90 and produces one letter for iteration.
const button = document.createElement('button');
-> creates a button.
const char = String.fromCharCode(i);
-> returns alphabets equivalent to ASCII
value. like 65 -> A, 66 -> B, .... 90 -> Z.
const span = document.createElement('span');
span.style.fontSize = '50px';
span.appendChild(document.createTextNode(char));
button.appendChild(span);
creates text to show on button
and appending it. Set fontSize
for better view.
document.body.appendChild(button);
-> Appending each button
to body
.
button.setAttribute('id', char);
button.style.padding = '30px';
button.style.margin = '10px';
setting id
attribute useful for firing click event and setting this as character itself. Also, setting some padding
and margin
for better view.
button.onclick = function () { getLetter(char) };
-> Setting onclick
for each button to trigger getLetter
function to perform action.
function getLetter(id) {
const letter = document.getElementById(id).textContent;
console.log(letter);
}
We are getting the button
by its id
and capturing its textContent
which basically the letter you clicked.
Next, printing to console
.
Here is the result:
That is it for today. I will try to improve further tomorrow.
Thanks😊 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)