Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 08.04.2021, 23:53
Аспирант
Отправить личное сообщение для tp-20 Посмотреть профиль Найти все сообщения от tp-20
 
Регистрация: 19.06.2018
Сообщений: 42

data атрибуты - из JS в jQuery
Задача: сделать на jQuery кнопку-переключатель тем - со светлой на тёмную.
на чистом JS работает, а на jQ не могу подобрать соответствующие функции.

всё, что мне надо, это по первому клику добавить к html дата-атрибут data-theme='dark'. И по второму клику - убрать атрибут. И так циклично.

не могу найти аналоги в jQuery для функций hasAttribute, removeAttribute и setAttribute.

Пример переключения темы:



дальше весь код.

const toggleBtn = document.querySelector("#toggle-theme");

        toggleBtn.addEventListener('click', (e) => {
            console.log("Switching theme");
            if (document.documentElement.hasAttribute('theme')) {
                document.documentElement.removeAttribute('theme');
            }
            else {
                document.documentElement.setAttribute('theme', 'dark');
            }
        });


<nav class="navbar">Title</nav>
    <div class="container">
        <div>
            <input type="button" value="Light/Dark" id="toggle-theme" />
            <label for="darkness">
                Darkness
            </label>
        </div>

        <h2 class="title">What is Lorem Ipsum?</h2>
        <p class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy
        </p>
    </div>

<style>  
        :root {
            --red-hue: 360;
            --blue-hue: 240;
            --green-hue: 120;
            --main-hue: var(--red-hue);
            --theme-darkness: 1;
            --nav-bg-color: hsl(var(--main-hue), 50%, 50%);
            --nav-text-color: hsl(var(--main-hue), 50%, 10%);
            --container-bg-color: hsl(var(--main-hue), 50%, 95%);
            --content-text-color: hsl(var(--main-hue), 50%, 50%);
            --title-color: hsl(--main-hue, 50%, 20%);
            --footer-bg-color: hsl(var(--main-hue), 93%, 88%);
            --button-text-color: hsl(var(--main-hue), 50%, 20%);
            filter: brightness(var(--theme-darkness));
        }

        :root[theme='dark'] {
            --red-hue: 360;
            --blue-hue: 240;
            --green-hue: 120;
            --main-hue: var(--blue-hue);
            --theme-darkness: 1;
            --nav-bg-color: hsl(var(--main-hue), 50%, 90%);
            --nav-text-color: hsl(var(--main-hue), 50%, 10%);
            --container-bg-color: hsl(var(--main-hue), 50%, 95%);
            --content-text-color: hsl(var(--main-hue), 50%, 50%);
            --title-color: hsl(--main-hue, 50%, 20%);
            --footer-bg-color: hsl(var(--main-hue), 93%, 88%);
            --button-text-color: hsl(var(--main-hue), 50%, 20%);
            filter: invert(1) brightness(var(--theme-darkness));
        }

        body {
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        nav {
            background: var(--nav-bg-color);
            color: var(--nav-text-color)
        }
        .container {
            flex: 1;
            background: var(--container-bg-color);
        }
        p.content {
            color: var(--content-text-color)
        }
        .container h2.title {
            color: var(--title-color)
        }
</style>

Последний раз редактировалось tp-20, 08.04.2021 в 23:56.
Ответить с цитированием
  #2 (permalink)  
Старый 09.04.2021, 01:03
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,059

tp-20,
Атрибуты и .is()
Ответить с цитированием
  #3 (permalink)  
Старый 09.04.2021, 01:14
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,059

tp-20,
<!DOCTYPE html>
<html>
<head>
    <title>Untitled</title>
    <meta charset="utf-8">
    <style>
        :root {
            --red-hue: 360;
            --blue-hue: 240;
            --green-hue: 120;
            --main-hue: var(--red-hue);
            --theme-darkness: 1;
            --nav-bg-color: hsl(var(--main-hue), 50%, 50%);
            --nav-text-color: hsl(var(--main-hue), 50%, 10%);
            --container-bg-color: hsl(var(--main-hue), 50%, 95%);
            --content-text-color: hsl(var(--main-hue), 50%, 50%);
            --title-color: hsl(--main-hue, 50%, 20%);
            --footer-bg-color: hsl(var(--main-hue), 93%, 88%);
            --button-text-color: hsl(var(--main-hue), 50%, 20%);
            filter: brightness(var(--theme-darkness));
        }
        :root[theme='dark'] {
            --red-hue: 360;
            --blue-hue: 240;
            --green-hue: 120;
            --main-hue: var(--blue-hue);
            --theme-darkness: 1;
            --nav-bg-color: hsl(var(--main-hue), 50%, 90%);
            --nav-text-color: hsl(var(--main-hue), 50%, 10%);
            --container-bg-color: hsl(var(--main-hue), 50%, 95%);
            --content-text-color: hsl(var(--main-hue), 50%, 50%);
            --title-color: hsl(--main-hue, 50%, 20%);
            --footer-bg-color: hsl(var(--main-hue), 93%, 88%);
            --button-text-color: hsl(var(--main-hue), 50%, 20%);
            filter: invert(1) brightness(var(--theme-darkness));
        }
        body {
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        nav {
            background: var(--nav-bg-color);
            color: var(--nav-text-color)
        }
        .container {
            flex: 1;
            background: var(--container-bg-color);
        }
        p.content {
            color: var(--content-text-color)
        }
        .container h2.title {
            color: var(--title-color)
        }
    </style>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(function() {
            $("#toggle-theme").on("click", function() {
                $("html").is("[theme]") ? $("html").removeAttr("theme") : $("html").attr("theme", "dark")
            })
        });
    </script>
</head>
<body>
    <nav class="navbar">Title</nav>
    <div class="container">
        <div>
            <input type="button" value="Light/Dark" id="toggle-theme" />
            <label for="darkness">
                Darkness
            </label>
        </div>
        <h2 class="title">What is Lorem Ipsum?</h2>
        <p class="content">
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy
        </p>
    </div>
</body>
</html>
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Просмотрела исходик jQuery Откорректируйте где не верно taksebe jQuery 5 23.11.2018 22:42
трансляция jQuery кода в нативный JS. winch jQuery 3 20.07.2018 11:49
Получить путь к выполняемому сценарию JS jQuery kosuha606 Общие вопросы Javascript 12 25.01.2016 19:00
jQuery, load: замена элемента вырубает js на странице. warobushek AJAX и COMET 0 08.10.2010 07:44
Вакансия: Front-end разработчик (HTML, CSS, JS, Ajax, jQuery) ivankov Работа 0 05.10.2010 19:00