Reputation: 45
Hi I need to know how I can add a transition effect when my theme stylesheet changes when clicking on the button. The following is my code.
document.addEventListener('DOMContentLoaded', () => {
const themeStylesheet = document.getElementById('theme');
const storedTheme = localStorage.getItem('theme');
if (storedTheme) {
themeStylesheet.href = storedTheme;
}
const themeToggle = document.getElementById('theme-toggley');
themeToggle.addEventListener('click', () => {
// if it's light -> go dark
if (themeStylesheet.href.includes('light')) {
themeStylesheet.href = 'css/dark-theme.css';
} else {
// if it's dark -> go light
themeStylesheet.href = 'css/light-theme.css';
}
// save the preference to localStorage
localStorage.setItem('theme', themeStylesheet.href)
})
})
<link id="theme" rel="stylesheet" type="text/css" href="css/light-theme.css" />
<button id="theme-toggley">Light</button>
Upvotes: 2
Views: 1081
Reputation: 693
just adding a
*{
transition-duration: 2s;
}
will work
eg:-
document.addEventListener('DOMContentLoaded', () => {
var lightTheme = document.getElementById('light-theme'),
darkTheme = document.getElementById("dark-theme");
var currentTheme;
function setTheme (themeId){
currentTheme = themeId;
document.querySelectorAll("link[rel=stylesheet].theme").forEach(link=>{
link.removeAttribute("rel");
})
document.querySelector(`#${themeId}`).setAttribute("rel","stylesheet");
}
const storedTheme = localStorage.getItem('theme');
if(storedTheme){
if(storedTheme == "light-theme"){
setTheme("dark-theme")
}else{
setTheme("light-theme")
}
}else{
setTheme("light-theme")
}
const themeToggle = document.getElementById('theme-toggley');
themeToggle.addEventListener('click', () => {
// if it's light -> go dark
if(currentTheme == "light-theme"){
setTheme("dark-theme")
} else {
// if it's dark -> go light
setTheme("light-theme")
}
// save the preference to localStorage
localStorage.setItem('theme',currentTheme)
})
})
*{
/*main*/
transition-duration: 2s;
}
button{
padding:10px ;border-radius:15px;
font-size: 20px;
}
<link id="light-theme" type="text/css" class="theme" href="data:text/css;utf8,button{ color : black; background-color: white ;}" />
<link id="dark-theme" type="text/css" class="theme" href="data:text/css;utf8,button{ color : white; background-color: black ;}" />
<button id="theme-toggley">Light</button>
Upvotes: 3