I just started front-end, want to implement a dark mode animation.
When you click the switch(a rope), the page will change theme.
but I don't know how to add the animation by using js like vue's class binding.
@keyframes line {
0% {
transform: translateY(0);
}
50% {
transform: translateY(100px);
}
100% {
transform: translateY(0);
}
}
.pull {
animation: line 0.5s;
}
just like this in vue(I found it online)
<div
class="switch"
:class="{ 'pull': inAnimation }"
@animationend="animationEnd"
@click="changeTheme"
/>
This is my code.
I don't konw how to use js to complete it.
const sw = document.getElementById('switch');
const changeTheme = () => {
sw.addEventListener("click", () => {
sw.className = 'pull';
if (document.body.className !== "dark") {
document.body.classList.add("dark");
localStorage.setItem("css", "dark");
} else {
document.body.classList.remove("dark");
localStorage.removeItem("css");
}
sw.className = '';
});
if (localStorage.getItem("css")) {
document.body.className = "dark";
document.body.classList.add("dark");
}
};
changeTheme();
First, I see that you miss the id the element because you're using getElementById,
it has to be like:
<div
id="switch" <!-- this is missing -->
class="switch"
:class="{ 'pull': inAnimation }"
@animationend="animationEnd"
@click="changeTheme"
/>
Then, Based on using Vue or not. (If Vue, setup the code in same component as in the element above).
Vue
<script>
export default {
mounted() {
const sw = document.getElementById('switch');
sw.addEventListener("click", () => {
sw.classList.add('pull');
if (!document.body.classList.contains("dark")) {
document.body.classList.add("dark");
localStorage.setItem("css", "dark");
} else {
document.body.classList.remove("dark");
localStorage.removeItem("css");
}
setTimeout(() => {
sw.classList.remove("pull")
}, 600);
});
if (localStorage.getItem("css")) {
document.body.classList.add("dark");
}
}
}
</script>
if Vanilla Js
const sw = document.getElementById("switch");
if (sw) {
const changeTheme = () => {
sw.addEventListener("click", () => {
sw.classList.add("pull");
if (!document.body.classList.contains("dark")) {
document.body.classList.add("dark");
localStorage.setItem("css", "dark");
} else {
document.body.classList.remove("dark");
localStorage.removeItem("css");
}
setTimeout(() => {
sw.classList.remove("pull");
}, 600);
});
if (localStorage.getItem("css")) {
document.body.classList.add("dark");
}
};
changeTheme();
}