1726168598

Toogle slider with css and javascript


```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Toggle Button</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="toggle-switch"> <input type="checkbox" id="switch" /> <label for="switch" class="slider"></label> </div> <!--Add the tag for the javascript code here.--> </body> </html> ``` CSS CODE ```css body { font-family: Arial, sans-serif; background-color: #333; color: white; display: flex; justify-content: center; align-items: center; height: 100vh; } .toggle-switch { position: relative; width: 60px; height: 34px; } .toggle-switch input { display: none; } .slider { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; border-radius: 34px; cursor: pointer; transition: 0.4s; } .slider:before { content: ""; position: absolute; width: 26px; height: 26px; border-radius: 50%; background-color: white; transition: 0.4s; top: 4px; left: 4px; } input:checked + .slider { background-color: #2196F3; } input:checked + .slider:before { transform: translateX(26px); } ``` Javascript(script.js) ```js document.getElementById('switch').addEventListener('change', function() { if (this.checked) { console.log("Switch is ON"); } else { console.log("Switch is OFF"); } }); ``` ![toogle](https://i.imgur.com/VgGgtks.png) **Explanation**: + The input type checkbox is hidden and styled using the label with the .slider class to simulate a slider button. + When the checkbox is checked, the background changes color and the circle inside the button slides to the right. + JavaScript listens to the change event on the checkbox to capture the state (on/off) and performs actions based on this. <br>This button can be used in various interfaces to switch settings or preferences.

(0) Comments

Welcome to Chat-to.dev, a space for both novice and experienced programmers to chat about programming and share code in their posts.

About | Privacy | Terms | Donate
[2024 © Chat-to.dev]