Virtual keyboard to write letters with accents that we do not have in Spanish

You can make a virtual keyboard with a series of buttons. Then you go through them with Javascript to assign an event to them that allows adding the necessary character to the web.

The first thing you need is to make sure that you use UTF-8 in the encoding of the HTML web document. You define this in the and then saving the file as utf-8 with the editor you use. With this first step you can start using those rare characters on your website that we do not have in the Spanish language or on the keyboard.

Text field and virtual keyboard buttons

Now you have the HTML of the text field and the virtual keyboard:

The text field has its identifier so that we can refer to it.

Then you have the buttons, which do not require an identifier for each one, but we are going to access them in a loop through their class. Each button has a data-attribute to define the key they should “virtually press” to type over the text field.

To make it look more like a keyboard you just need to apply some CSS:

.virtualkeyboard { margin: 1rem 0; padding: 1rem; background: #eee; width: 200px; text-align:center; } .virtualkey { background: #444; color: #fff; border: none; border-radius: 0.3rem; padding: 0.3rem 0.4rem; }

Associate the click event to the virtual keyboard keys

We then make a loop to assign a click event to all buttons:

var targetElement = document.getElementById(‘targettext’); document.querySelectorAll(“.virtualkey”).forEach(function(item) { item.addEventListener(‘click’, function() { console.log(item.dataset.char); targetElement.value += item.dataset.char ; }) })

With this you already have the necessary functionality in your virtual keyboard and the characters you need will be written in the text field. You can have any number of buttons, it will work just the same. You just need to make sure that all buttons have:

  • The “virtualkey” CSS class
  • A data attribute defined with data-char=”å” obviously, placing the character you need for that virtual keyboard key.
See also  How and why to learn programming with Javascript

You can see here. Although now that I think about it, you could simply use the value of the button itself to find out what character is associated with it. But well, with the data attribute you make sure that you can use any type of label for this virtual keyboard, even images if necessary.

Loading Facebook Comments ...
Loading Disqus Comments ...