Creating a Toggle Button using HTML5 CSS3 and JavaScript

Let’s look how to create Toggle Button. We will cover prettying up using CSS and CSS3.

Before we get started, we need to create a HTML page. So lets create a HTML page.

Setting up HTML page

In my case I always use Visual Studio Code editor to create my any web applications. So create a new index.html file in your new project folder. Just type ‘html’ word and you will get a list of html templates. Select ‘html5’. Here is your HTML basic code must be generated

Now link style.css, script.js, toggle-button.css and toggle.js. So your HTML something look like below code.

Now create style.css, script.js, toggle-button.css and toggle.js in your project folder.

HTML Structure for Toggle Button

Let’s add HTML for Toggle Button.

As you can see inside button parent div we have created a container and inside that a handle to switch on off.

Style a Toggle Button

Now we have to style it. Open toggle-btn.css and first style the container as a button background. Here will apply horizontal linear gradient to container background. See the CSS below.

The button must be look like below snapshot.

As you can see we have set the container size 100 x 50 pixels And we have setup container half background color
as green and half background as gray.

Now style the button handle. Set its width and height 50 pixels as well set animation-fill-mode as forward and duration 0.1s.

Now to move the handle button, we will use CSS animation. Define two animation sequences in CSS. One for to move to the right to ON the switch and other one for move to left to switch OFF button.

In above code you can see, How I have setup start and end point of handle position setting its left position value.

Once you done everything with CSS. The preview must be look like below image.

Make Toggle Button Interactive

Now its time to make the button interactive. So open the toggle-btn.js you created and define ToggleButton class. See the code below.

In above code you can see in on_click(e) handler how the animation name is switched as per its current state.

Implementing Toggle Button

Once class is created now its time make it functional in HTML page. So open the script.js and add the below code.

Now refresh the page and try clicking on button.

Download source from here

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *