Discover postsExplore captivating content and diverse perspectives on our Discover page. Uncover fresh ideas and engage in meaningful conversations
To create a toggle button in JavaScript, you can use a simple HTML button element and toggle its state using a variable or a class. Here's an example:
```html
<!DOCTYPE html>
<html>
<head>
<title>Toggle Button</title>
</head>
<body>
<button id="toggleButton">Toggle</button>
<script>
const button = document.getElementById('toggleButton';
let isToggled = false;
button.addEventListener('click', () => {
isToggled = !isToggled;
if(isToggled){
button.textContent = 'On';
button.classList.add('active';
} else {
button.textContent = 'Off';
button.classList.remove('active';
}
});
</script>
<style>
.active {
background-color: green;
color: white;
}
</style>
</body>
</html>
```
In this example, we have a button element with the ID 'toggleButton'. We also have a variable 'isToggled' which keeps track of the state of the button. When the button is clicked, we toggle the state of the button and update its text content and class based on the state.
You can customize the appearance of the button by adding styles to the 'active' class in the `<style>` tag.