I’m looking for a good solution to switch day/night css class with Kirby. The problem is to save the user setting without Database or JS. I already tried a Javascript way but the css is loaded after the dom is ready.
Yes but I don’t have any knowledge about how cookies are working. After searching in the forum, I tried to start by a php else/if statement I found here.
<body class="<?php if(!cookie::exists('accepted')): ?>
day
<?php else(cookie::set('accepted', 'true', 1440*365)): ?>
night
<?php endif ?>
">
But I don’t know how to activate it (by JS I suppose) by clicking <button class="daynight" onclick="daynight()">🔌</button>
Thank you very much for this, I could start something, including the cookie.js plugin, the switch function is running, but when the page is refreshed, the style is “blinking” as if it comes after the dom
$(function() {
// Check (onLoad) if the cookie is there and set the class if it is
if ($.cookie('highcontrast') == "yes") {
$("body").addClass("highcontrast");
}
// When the span is clicked
$("#switch").click(function () {
// Check the current cookie value
// If the cookie is empty or set to no, then add highcontrast
if ($.cookie('highcontrast') == "undefined" || $.cookie('highcontrast') == "no") {
// Set cookie value to yes
$.cookie('highcontrast','yes', {expires: 7, path: '/'});
// Add the class to the body
$("body").addClass("highcontrast");
}
// If the cookie was already set to yes then remove it
else {
$.cookie('highcontrast','no', {expires: 7, path: '/'});
$("body").removeClass("highcontrast");
}
});
});
Now, the toggleClass is working, the cookie is saved, but the style is “blinking” on page load, as if it comes after (btw if I remove the <?php if(cookie::get('highcontrast') == 'yes') { echo 'highcontrast';} ?> line it is the same thing).
Ok, I simply changed the template into <body class="<?php if(a::get($_COOKIE, 'highcontrast') == 'yes') { echo 'highcontrast';} ?>"> and removed these lines :
// Check (onLoad) if the cookie is there and set the class if it is
if ($.cookie('highcontrast') == "yes") {
$("body").addClass("highcontrast");
}
And this is working very fine. If anyone finds a better way, don’t hesitate !