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?
2
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>
You can look into using CSS properties/variables to define the different styles for your themes (this way you can avoid defining the styles 3 times for each theme for every class that you have), and then apply the theme with the variable definitions to a root element such as your body:
const btn = document.querySelector("#change-theme-btn");
let themeIdx = 0;
const themes = ["theme1", "theme2", "theme3"];
function setTheme() {
document.body.classList.remove(...themes);
const nextTheme = themes[themeIdx++ % themes.length];
document.body.classList.add(nextTheme);
}
btn.addEventListener("click", setTheme);
setTheme();
.theme1 {
--primary-bg-color: yellow;
--primary-text-color: red;
}
.theme2 {
--primary-bg-color: black;
--primary-text-color: white;
}
.theme3 {
--primary-bg-color: cyan;
--primary-text-color: black;
}
body {
background-color: var(--primary-bg-color);
}
.text {
color: var(--primary-text-color);
}
<p class="text">Text</p>
<button id="change-theme-btn">Change theme</button>