Back
Learn to create a flexible toggle button that smoothly transitions between multiple states with easy customization options.
<div class="toggle-container"> <button id="multi-toggle" class="toggle-button"> <span class="toggle-state">State 1</span> </button> </div>
.toggle-container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #ecf0f1; } .toggle-button { padding: 10px 20px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; background-color: #f1c40f; } .toggle-state { color: #fff; }
let currentState = 0; const states = ['State 1', 'State 2', 'State 3']; function toggleState() { currentState = (currentState + 1) % states.length; document.querySelector('.toggle-state').textContent = states[currentState]; const toggleButton = document.getElementById('multi-toggle'); toggleButton.style.backgroundColor = currentState === 0 ? '#f1c40f' : currentState === 1 ? '#e74c3c' : '#8e44ad'; } document.getElementById('multi-toggle').addEventListener('click', toggleState);
<div class="toggle-container"> <button id="multi-toggle" class="toggle-button"> <span class="toggle-state">State 1</span> </button> </div> <script> let currentState = 0; const states = ['State 1', 'State 2', 'State 3']; function toggleState() { currentState = (currentState + 1) % states.length; document.querySelector('.toggle-state').textContent = states[currentState]; const toggleButton = document.getElementById('multi-toggle'); toggleButton.style.backgroundColor = currentState === 0 ? '#f1c40f' : currentState === 1 ? '#e74c3c' : '#8e44ad'; } document.getElementById('multi-toggle').addEventListener('click', toggleState); </script> <style> .toggle-container { display: flex; justify-content: center; align-items: center; height: 100vh; background-color: #ecf0f1; } .toggle-button { padding: 10px 20px; font-size: 16px; border: none; border-radius: 5px; cursor: pointer; transition: background-color 0.3s ease; background-color: #f1c40f; } .toggle-state { color: #fff; } </style>Thank you for reading this article.
Comments
No comments yet. Be the first to comment!