Answer the question
In order to leave comments, you need to log in
How to change the theme on the site?
Good day friends! How to change the href of a styled link with jQuery ?
In order to make a dark theme on the site. For example, there is a button:
<button data-theme="css/main.dark.css">Темная</button>
<link rel="stylesheet" type="text/css" href="css/main.light.css">
<link rel="stylesheet" type="text/css" href="css/main.dark.css">
Answer the question
In order to leave comments, you need to log in
If you want to change styles without reloading, then you need to find the element with the old styles, deactivate it
document.querySelector('link[href*="light"]').disabled=true;
document.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" type="text/css" href="css/main.dark.css">');
function getTheme() {
return localStorage.getItem('theme') || 'light'; // default light
}
function toggleTheme() {
let newTheme, oldTheme;
if (getTheme() === 'light') {
newTheme = 'dark';
oldTheme = 'light';
} else {
newTheme = 'light';
oldTheme = 'dark';
}
document.querySelector(`link[href*="${oldTheme}"]`).disabled=true;
document.head.insertAdjacentHTML('beforeend', `<link rel="stylesheet" type="text/css" href="css/main.${newTheme}.css">`);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question