Answer the question
In order to leave comments, you need to log in
How to make DarkMode on a site without css substitution, but only with html substitution?
In general, that is, index.html and dark.html
need to be done somehow so that when the button is pressed, html is replaced and remembered in cookies, but without reloading the page. I have an idea to implement this using page tabs, please help, give the code, what, where and how to do? I couldn't find anything on google about this! I wanted to do the method of changing multilingualism, but I didn’t find anything necessary there either.
Replacing css is not an option, because there are problems with icons, color inversion and (html files based on bootstrap css and load them from the server, so not an option at all, I tried it already, you don’t have to ask)
I would be grateful for your help! Thanks in advance.
Answer the question
In order to leave comments, you need to log in
1KirillIvanov , Well, if you have such css, Then it is solved in a couple of lines of js
Exactly when the element has
let allElem = document.querySelectorAll('[class$="light"]')//Ищем все элементы у которых в конце есть приставка light
allElem.forEach(item=>{
item.className = item.className.replace(/light/g, "dark");
});
<!DOCTYPE html>
<html data-mode="dark">
<head>
<title>Site</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="theme.css">
</head>
<body>
<h1>Тест</h1>
<button class="theme-button" id="js-theme-button">Переключить стиль</button>
<script type="text/javascript" src="themes.js"></script>
</body>
</html>
:root {
--bg-base: #444;
--color-text: #000
}
[dark-mode=dark]
:root {
--bg-base: #000;
--color-text: #fff
}
body {
background: var(--bg-base);
color: var(--color-text);
}
<!DOCTYPE html>
<html>
<head>
<title>Site</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="theme-dark.css">
<link rel="stylesheet" type="text/css" href="theme-light.css" id="theme-link">
</head>
<body>
<h1>Тест</h1>
<button class="theme-button" id="js-theme-button">Переключить стиль</button>
<script type="text/javascript" src="themes.js"></script>
</body>
</html>
var btn = document.getElementById("js-theme-button");
var link = document.getElementById("theme-link");
btn.addEventListener("click", function () {
ChangeTheme();
});
function ChangeTheme() {
let lightTheme = "theme-light.css";
let darkTheme = "theme-dark.css";
var currentTheme = link.getAttribute("href");
var theme = "";
if (currentTheme == lightTheme) {
currentTheme = darkTheme;
theme = "dark";
}
else {
currentTheme = lightTheme;
theme = "light";
}
link.setAttribute("href", currentTheme);
Save(theme);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question