Skip to content
Advertisement

virtual keyboard in JS but with images

I want to make a virtual keyboard in HTML, CSS, and JavaScript. However, there is a twist. Instead of the letters on the keyboard, I would like to replace them with images of my own choice. So lets say,

instead of letter "a", i have an image of APPLE
instead of letter "s", I have an image of SNAKE

Was able to do it.

Advertisement

Answer

is this what you had in mind?

var elements = document.getElementsByClassName("key");

var myFunction = function(event) {
let text = document.getElementById('text')
text.innerText = text.innerText + event.target.id
   
};

for (var i = 0; i < elements.length; i++) {
    elements[i].addEventListener('click', myFunction, false);
}
.keyboard{
display:flex;
justify-content:center;
}

img{
border:solid 2px green;
}
<div class='keyboard'>
<img src="https://unsplash.it/50/50.jpg?image=1" id='a' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=2" id='b' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=3" id='c' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=4" id='d' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=5" id='e' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=6" id='f' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=7" id='g' class='key'> 
</div>
<div class='keyboard'>
<img src="https://unsplash.it/50/50.jpg?image=81" id='h' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=82" id='i' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=83" id='j' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=84" id='k' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=85" id='l' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=88" id='m' class='key'> 
<img src="https://unsplash.it/50/50.jpg?image=87" id='n' class='key'> 
</div>

<div id='text'>

</div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement