Search code examples
javascripthtmlcss

Javascript-How can I change style of my app in a click and change again in a second click and return to my initial style in third click


I'm making a calculator with Javascript and I want to make a button that if I click on it whole style of my project changes and if I click again whole style changes again and at third click it returns to initial style

I don't have any Idea how I can change whole style for three times just with one button?


Solution

  • You can create different css classes and put them in an array. Everytime you click on a button you can switch styles by changing index. Since you did not provide any code here is an example.

    let styleIndex = 0;
    const styles = ['style1', 'style2', 'style3']; // styles array
    
    function changeStyle() {
        styleIndex = (styleIndex + 1) % styles.length;
        document.body.className = styles[styleIndex];
    }
    body.style1 {
        background-color: white;
        color: black;
    }
    
    body.style2 {
        background-color: black;
        color: white;
    }
    
    body.style3 {
        background-color: blue;
        color: yellow;
    }
    
    /* You can change the css classes depends on your choice and application */
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Calculator</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body class="style1">
        <button onclick="changeStyle()">Click to change background color</button>
        <script src="script.js"></script>
    </body>
    </html>