M
M
MentozZz ORG2021-09-17 22:18:43
JavaScript
MentozZz ORG, 2021-09-17 22:18:43

How to store button clicks in localstorage?

How to save button click in local storage or cookie

here is html

<div class="theme-kn">
                <i class="fa-solid fa-lightbulb-on theme-i getdark" aria-hidden="true"></i><i class="fa-solid fa-lightbulb-slash theme-i getlight"></i>
    </div>


here is js

$('.getlight').click(function () {
                $('link[href="templates/gor/css/light.css"]').attr('href', 'templates/gor/css/dark.css');
            });
$('.getdark').click(function () {
                $('link[href="templates/gor/css/dark.css"]').attr('href', 'templates/gor/css/light.css');
            });

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey delphinpro, 2021-09-17
@delphinpro

First, set an identifier to the tag with the style connection

<link id="theme" href="templates/gor/css/light.css">

Then define a function
function setTheme(theme) {
  document.getElementById('theme').setAttribute('href', `templates/gor/css/${theme}.css`);
}

Then you can use it
$('.getlight').on('click', function () {
  setTheme('light');
  localStorage.setItem('selectedTheme', 'light'); // Запомнить
});
$('.getdark').on('click', function () {
  setTheme('dark');
  localStorage.setItem('selectedTheme', 'dark'); // Запомнить
});

and set the theme to the chosen theme on page load
const selectedTheme = localStorage.getItem('selectedTheme') ?? 'light';
setTheme(selectedTheme);

A
Alexey Sklyarov, 2021-09-18
@0example

Look Away: Create A Dark/Light Mode Switch with CSS Variables

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question