DEV Community

Cover image for How to build a piano with only HTML, CSS, Javascript ?
Lotfi Jebali
Lotfi Jebali

Posted on • Updated on

How to build a piano with only HTML, CSS, Javascript ?

In this post, we’ll learn how to build this piano from scratch using simple HTML, CSS, and JavaScript.

Firstly, we’ll structure our web app using HTML. We’ll use the main tag to make a wrapper structure for the piano.

We will create classes to show white and black keys, and classes will be further used in CSS for designing.

I added a class empty to some black keys because we don't need the same amount of white keys and I tried to do it the simple way.

In script.js, I grabbed all keys with className to make an array of all keys and created an array of sounds.

I, then, iterated through every single element of array keys and added a click event to play a random sound.

I, also, created a play() function to play a random sound on every keyboard button press on body element (I don't recommend that but I wanted to make it simple).

I created a sounds folder where I stored 21 different sounds of piano keys.

index.html

HTML

style.css ( click to zoom )

CSS

script.js

JS

NOTE :
There is room for improvement and this is only for beginners who just started as it covers simple concepts.

Top comments (0)