Skip to content

Instantly share code, notes, and snippets.

@redamoon
Created Jan 5, 2021
Embed
What would you like to do?
xxEjXNX
<div class="header">
<h1><a href="/">www.ni4.jp</a></h1>
<div class="mode-change">
<input type="checkbox" name="view-mode" id="view-mode">
<label for="view-mode">mode: </label>
</div>
</div>
$(function () {
const $body = $('body');
const getCookie = $.cookie('dark');
function labelChange(mode) {
const $modeChangeLabel = $('.mode-change label');
mode ? $modeChangeLabel.addClass('dark-move') : $modeChangeLabel.removeClass('dark-move');
mode ? $modeChangeLabel.removeClass('light-move') : $modeChangeLabel.addClass('light-move');
return getMode(mode);
}
function getMode(type) {
// typeの引数でonとoffを判別
const check = type ? 'on' : 'off';
type ? $body.addClass('dark') : $body.addClass('light');
type ? $body.removeClass('light') : $body.removeClass('dark');
$('input[name="view-mode"]').prop('checked', type);
$.cookie('dark', check, { expires: 365, path:'/'});
}
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
$.cookie('dark') === 'off' ? getMode(false) : getMode(true);
} else {
$.cookie('dark') === 'on' ? getMode(true) : getMode(false);
}
$('input[name="view-mode"]').change(function(){
const checkedFlg = $(this).is(':checked');
checkedFlg ? labelChange(true) : labelChange(false);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
.light {
transition: 0.3s;
}
.dark {
transition: 0.3s;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://www.ni4.jp/common/style.css" rel="stylesheet" />
<link href="https://www.ni4.jp/common/darkmode.css" rel="stylesheet" />
<link href="https://www.ni4.jp/common/mode-change.css" rel="stylesheet" />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment