Creating a stylish switch button with Html and CSS

I came across a fantastic tool for creating CSS buttons . I have created a switch button and I know that I need to run two JS codes - one for when the switch is on (alert("on")) and another for when it's off (alert("off")). Could you please assist me with this? Below is the HTML and CSS code:

<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
<label class="onoffswitch-label" for="myonoffswitch">
<div class="onoffswitch-inner"></div>
<div class="onoffswitch-switch"></div>
</label>
</div>


<style type="text/css">
    .onoffswitch {
      position: relative;
      width: 82px;
      -webkit-user-select:none;
      -moz-user-select:none;
      -ms-user-select: none;
    }
    .onoffswitch-checkbox {
      display: none;
    }
    .onoffswitch-label {
      display: block; overflow: hidden; cursor: pointer;
      border: 2px solid #FFFFFF; border-radius: 5px;
    }
    .onoffswitch-inner {
      width: 200%;
      margin-left: -100%;
      -moz-transition: margin 0.3s ease-in 0s;
      -webkit-transition: margin 0.3s ease-in 0s;
      -o-transition: margin 0.3s ease-in 0s;
      transition: margin 0.3s ease-in 0s;
    }
    .onoffswitch-inner:before, .onoffswitch-inner:after {
    float: left; width: 50%; height: 24px; padding: 0; line-height: 24px;
    font-size: 18px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
    -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;
    }
    .onoffswitch-inner:before {
      content: "on";
      padding-left: 14px;
      background-color: #2FFF3D;
      color: #FFFFFF;
    }
    .onoffswitch-inner:after {
      content: "off";
      padding-right: 14px;
      background-color: #ADADAD;
      color: #FFFFFF;
      text-align: right;
    }
    .onoffswitch-switch {
      width: 28px; margin: 0px;
      background: #FFFFFF;
      border: 2px solid #FFFFFF; border-radius: 5px;
      position: absolute; top: 0; bottom: 0; right: 50px;
      -moz-transition: all 0.3s ease-in 0s; -webkit-transition: all 0.3s ease-in 0s;
      -o-transition: all 0.3s ease-in 0s; transition: all 0.3s ease-in 0s;
      background-image: -moz-linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%);
      background-image: -webkit-linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%);
      background-image: -o-linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%);
      background-image: linear-gradient(center top, rgba(0,0,0,0.1) 0%, rgba(0,0,0,0) 100%);
    }
    .onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
      margin-left: 0;
    }
    .onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
      right: 0px;
    }
</style>

Answer №1

Here is a quick example of how JQuery can be used:

$('#myonoffswitch').on('change', function() {
    if ($(this).is(':checked')) {
         alert("ON")   
    } else {
         alert("OFF")   
    }
});

If you prefer the function to run after an animation, you can try this alternative:

$('#myonoffswitch').on('change', function() {
        if ($(this).is(':checked')) {
            setTimeout(function() {
                alert("ON")
            }, 334); 
        } else {
            setTimeout(function() {
                alert("OFF")
            }, 334);  
        }
});

Answer №2

If you're looking for a recommendation, I suggest utilizing JQuery as 3rror404 has mentioned.

However, if you prefer to stick with pure Javascript, you can achieve something similar by following this example:

HTML

<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" onchange="changeSwitch()" checked>

JS

function changeSwitch() {
     var isChecked = document.getElementById("myonoffswitch").checked;
     if(isChecked) {
         //perform actions when the checkbox is checked
         alert('ON')
     }
    else {
        //perform actions when the checkbox is not checked
        alert('OFF');
    }
}

Check out the demo here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is $(window).load() being executed twice?

When using $(window).load() to resize images in a thumbnail gallery and set up a slideshow, the code seems to be running twice. This can be observed by noticing that a div is being wrapped around another div twice when inspecting the HTML on page load. Af ...

The issue arises when trying to set the height of the modal body correctly while using ng-bootstrap to open the modal as a separate component

There seems to be an issue with the height not being properly added in the modal body when the modal is opened as a separate component using ng-bootstrap. The problem can be seen in the following link: https://i.sstatic.net/natkn.png https://stackblitz.co ...

What is the best approach to creating a fully rounded capsule using CSS?

I've been having trouble creating a complete capsule in CSS and I'm not achieving the expected outcome. Can anyone assist me in resolving this issue? I am new to CSS. Below is my code: <style> #myStyle { position: relat ...

CSS animation properties

Is it possible to animate only the div container and not the "p" inside? div { width: 100px; height: 100px; background-color: red; -webkit-animation-name: example; /* Safari 4.0 - 8.0 */ -webkit-animation-duration: 4s; /* Safari 4.0 ...

Node containing clickable buttons

TL;DR - Can we implement functional links within a jsTree node without resorting to JavaScript redirection? I am interested in incorporating buttons inside a jsTree node, like so: This was my initial attempt: $('#tree').jstree({ &apos ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

The icons in my navigation menu appear differently in Safari compared to Firefox

Having some trouble with the vertical alignment of navigation menu icons in Safari and Firefox. Any suggestions on how to fix this issue? HTML <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-tra ...

Is there a way to dynamically modify a website's default viewport settings in a mobile browser?

When viewing a website in Landscape mode, everything looks good. However, switching to Portrait mode displays the message "Screen size not supported." I decided to test this on my desktop browser and discovered that adjusting the initial-scale:1 to initial ...

Django: Limit available selections based on preceding model choices made

I am managing multiple models: class Game(models.Model): name = models.CharField('Nom du jeu', max_length=100) logo = models.ImageField('Logo', blank=True, upload_to='game_logos') class League(models.Model): game ...

JS: Looking to add animation with a button click?

Looking for feedback on my code to animate/colorify the div when clicking the 'Animate' button. Any suggestions or additional code are welcome! This is how my code currently looks: .anime { animation: coloranimate 5s; width: 100px; heig ...

Transforming HTML into a DOCX document

I am exploring all possible options for converting an HTML document to a DOCX file. Background : I have some simple documentation in HTML (just basic elements like H1, H2, P, IMG), and I want to transform it into Word documents. An ideal solution would ...

Secure your online file with a password

I need to access a specific file on my computer through a program, not a web browser. However, I want to ensure that only authorized users can view the file by requiring a password with the request. How can I set up the file to prompt for a password befor ...

Utilize JavaScript objects to convert subscripts into HTML elements

I am currently developing an Angular 1X application where all icon labels are stored in a JS object as shown below: var labels={ ........ iconlabel_o2:"O<sub>2</sub>", iconLabel_co2:"CO<sub>2</sub>", iconLabel_h20:"H<sub ...

Z-index creates an obstacle that prevents items from being clicked on

I am facing an issue with my container div that has an inset drop shadow applied to it. Inside this container, I have child elements and I want these children to be clickable. For the drop shadow to show, it is necessary to set the z-index of the child el ...

Using absolute positioning on elements can result in the page zooming out

While this answer may seem obvious, I have been unable to find any similar solutions online. The problem lies with my responsive navbar, which functions perfectly on larger screens. However, on mobile devices, the entire website appears zoomed out like thi ...

The animated 3D cube is specifically compatible with Firefox

After working on a 3D animated cube that rotates infinitely in two angles, I encountered some browser compatibility issues. The cube can be found on the home page of our new company website (next to the Software title when scrolling down) at test website. ...

Toggle the submit button using jQuery based on the comparison of the jml_automatic field with the id_km field

I recently learned jQuery last month, and now I am working on a form using jQuery to allow users to input gas requests. However, the script is not working to compare the values from #jml_km with #id_km, and the submit button is still not disabled when the ...

Enhancing OpenSeadragon images with custom overlays and managing error messages

Currently, I am experimenting with the Basic Single-Row Tile Source Collection example using the same configurations and tile sources outlined in the example. However, I am encountering difficulties in adding overlays to the first and second images as int ...

Choose the Nth option in the dropdown list using programming

Currently, I have a script that dynamically populates a select box with unknown values and quantities of items. I am looking to create another script that mimics the action of selecting the Nth item in that box. Despite my research, I have been unable to ...

Step-by-step guide on embedding a function in HTML using vbscript

I'm working on a dynamic HTML list that I want to enable or disable based on user input. Typically, you can just use the "enabled" or "disabled" attribute at the end of the select element to control the entire list. However, I'm unsure how to ach ...