V
V
valgerofficial2021-06-23 17:55:20
JavaScript
valgerofficial, 2021-06-23 17:55:20

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>


By clicking on it, from standard styles:

<link rel="stylesheet" type="text/css" href="css/main.light.css">


They change to:

<link rel="stylesheet" type="text/css" href="css/main.dark.css">


And here's another question, about saving values? So that the next time you enter the site, the user will see the theme he chose, either Light or Dark. Thanks!)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2021-06-23
@Stalker_RED

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;

and add another file
document.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" type="text/css" href="css/main.dark.css">');

Saving can be done in localStorage
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 question

Ask a Question

731 491 924 answers to any question