mirror of
https://github.com/jakejarvis/jarv.is.git
synced 2025-04-27 13:56:22 -04:00
clean up scripts
This commit is contained in:
parent
759bae4f14
commit
9e1a053d39
@ -2,32 +2,35 @@
|
|||||||
|
|
||||||
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
|
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
|
||||||
|
|
||||||
(function() {
|
(function () {
|
||||||
// improve variable mangling when minifying
|
// improve variable mangling when minifying
|
||||||
var win = window;
|
var win = window;
|
||||||
var doc = win.document;
|
var doc = win.document;
|
||||||
var bod = doc.body;
|
var body = doc.body;
|
||||||
var cls = bod.classList;
|
var classes = body.classList;
|
||||||
var sto = localStorage;
|
var storage = localStorage;
|
||||||
|
|
||||||
// check for preset `dark_mode_pref` preference in localStorage
|
// check for preset `dark_mode_pref` preference in local storage
|
||||||
var pref_key = 'dark_mode_pref';
|
var pref_key = 'dark_mode_pref';
|
||||||
var pref = sto.getItem(pref_key);
|
var pref = storage.getItem(pref_key);
|
||||||
|
|
||||||
// change CSS via these <body> classes:
|
// change CSS via these <body> classes:
|
||||||
var dark = 'dark';
|
var dark = 'dark';
|
||||||
var light = 'light';
|
var light = 'light';
|
||||||
|
|
||||||
|
// which class is <body> set to initially?
|
||||||
|
var default_theme = light;
|
||||||
|
|
||||||
// use an element with class `dark-mode-toggle` to trigger swap when clicked
|
// use an element with class `dark-mode-toggle` to trigger swap when clicked
|
||||||
var toggle = doc.querySelector('.dark-mode-toggle');
|
var toggle = doc.querySelector('.dark-mode-toggle');
|
||||||
|
|
||||||
// keep track of current state (light by default) no matter how we got there
|
// keep track of current state no matter how we got there
|
||||||
var active = false;
|
var active = (default_theme === dark);
|
||||||
|
|
||||||
// receives a class name and switches <body> to it
|
// receives a class name and switches <body> to it
|
||||||
var activateTheme = function(theme) {
|
var activateTheme = function (theme) {
|
||||||
cls.remove(dark, light);
|
classes.remove(dark, light);
|
||||||
cls.add(theme);
|
classes.add(theme);
|
||||||
active = (theme === dark);
|
active = (theme === dark);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -37,18 +40,23 @@
|
|||||||
|
|
||||||
// user has never clicked the button, so go by their OS preference until/if they do so
|
// user has never clicked the button, so go by their OS preference until/if they do so
|
||||||
if (!pref) {
|
if (!pref) {
|
||||||
// check for OS dark mode setting and switch accordingly
|
// returns media query selector syntax
|
||||||
var prefers_dark = '(prefers-color-scheme: dark)';
|
var prefers = function (theme) {
|
||||||
var prefers_light = '(prefers-color-scheme: light)';
|
return '(prefers-color-scheme: ' + theme + ')';
|
||||||
|
};
|
||||||
|
|
||||||
if (win.matchMedia(prefers_dark).matches)
|
// check for OS dark/light mode preference and switch accordingly
|
||||||
|
// default to `default_theme` set above if unsupported
|
||||||
|
if (win.matchMedia(prefers(dark)).matches)
|
||||||
activateTheme(dark);
|
activateTheme(dark);
|
||||||
else
|
else if (win.matchMedia(prefers(light)).matches)
|
||||||
activateTheme(light);
|
activateTheme(light);
|
||||||
|
else
|
||||||
|
activateTheme(default_theme);
|
||||||
|
|
||||||
// real-time switching if supported by OS/browser
|
// real-time switching if supported by OS/browser
|
||||||
win.matchMedia(prefers_dark).addListener(function(e) { if (e.matches) activateTheme(dark); });
|
win.matchMedia(prefers(dark)).addListener(function (e) { if (e.matches) activateTheme(dark); });
|
||||||
win.matchMedia(prefers_light).addListener(function(e) { if (e.matches) activateTheme(light); });
|
win.matchMedia(prefers(light)).addListener(function (e) { if (e.matches) activateTheme(light); });
|
||||||
}
|
}
|
||||||
|
|
||||||
// don't freak out if page happens not to have a toggle
|
// don't freak out if page happens not to have a toggle
|
||||||
@ -57,18 +65,18 @@
|
|||||||
toggle.style.visibility = 'visible';
|
toggle.style.visibility = 'visible';
|
||||||
|
|
||||||
// handle toggle click
|
// handle toggle click
|
||||||
toggle.addEventListener('click', function() {
|
toggle.addEventListener('click', function () {
|
||||||
// switch to the opposite theme & save preference in local storage
|
// switch to the opposite theme & save preference in local storage
|
||||||
if (!active) {
|
if (active) {
|
||||||
activateTheme(dark);
|
|
||||||
sto.setItem(pref_key, dark);
|
|
||||||
// send click event to analytics
|
|
||||||
sa_event('triggered_dark_mode');
|
|
||||||
} else {
|
|
||||||
activateTheme(light);
|
activateTheme(light);
|
||||||
sto.setItem(pref_key, light);
|
storage.setItem(pref_key, light);
|
||||||
// send click event to analytics
|
// send event to SA
|
||||||
sa_event('triggered_light_mode');
|
sa_event('triggered_light_mode');
|
||||||
|
} else {
|
||||||
|
activateTheme(dark);
|
||||||
|
storage.setItem(pref_key, dark);
|
||||||
|
// send event to SA
|
||||||
|
sa_event('triggered_dark_mode');
|
||||||
}
|
}
|
||||||
}, true);
|
}, true);
|
||||||
}
|
}
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
/* jshint browser: true, laxbreak:true, -W080 */
|
/* jshint browser: true, laxbreak:true, -W080 */
|
||||||
|
|
||||||
/*! Simple Analytics - Privacy friendly analytics (docs.simpleanalytics.com/script; 2020-03-02; 21e2) */
|
/*! Simple Analytics - Privacy friendly analytics (docs.simpleanalytics.com/script; 2020-05-03; d98d) */
|
||||||
// https://github.com/simpleanalytics/scripts/blob/3918189e9137b55522a2dbeb3d7cb4bc2c26c52a/src/default.js
|
// https://github.com/simpleanalytics/scripts/blob/915d98d39868cbb578619f64b5e2374a5af60c2b/src/default.js
|
||||||
|
|
||||||
(function(window, baseUrl, apiUrlPrefix, version, saGlobal) {
|
(function (window, baseUrl) {
|
||||||
if (!window) return;
|
if (!window) return;
|
||||||
|
|
||||||
// Generate the needed variables, this seems like a lot of repetition, but it
|
// Generate the needed variables, this seems like a lot of repetition, but it
|
||||||
@ -17,6 +17,7 @@
|
|||||||
var slash = "/";
|
var slash = "/";
|
||||||
var nav = window.navigator;
|
var nav = window.navigator;
|
||||||
var loc = window.location;
|
var loc = window.location;
|
||||||
|
var hostname = loc.hostname;
|
||||||
var doc = window.document;
|
var doc = window.document;
|
||||||
var notSending = "Not sending requests ";
|
var notSending = "Not sending requests ";
|
||||||
var encodeURIComponentFunc = encodeURIComponent;
|
var encodeURIComponentFunc = encodeURIComponent;
|
||||||
@ -26,42 +27,46 @@
|
|||||||
var addEventListenerFunc = window.addEventListener;
|
var addEventListenerFunc = window.addEventListener;
|
||||||
var fullApiUrl = protocol + baseUrl;
|
var fullApiUrl = protocol + baseUrl;
|
||||||
var undefinedVar = undefined;
|
var undefinedVar = undefined;
|
||||||
var hostname = loc.hostname;
|
|
||||||
var functionName = "sa_event";
|
var functionName = "sa_event";
|
||||||
|
|
||||||
var payload = {
|
var payload = {
|
||||||
version: 2
|
version: 2,
|
||||||
};
|
};
|
||||||
|
|
||||||
payload.hostname = hostname;
|
var options = {
|
||||||
|
hostname: hostname,
|
||||||
|
functionName: functionName,
|
||||||
|
};
|
||||||
|
|
||||||
|
payload.hostname = options.hostname;
|
||||||
|
|
||||||
// A simple log function so the user knows why a request is not being send
|
// A simple log function so the user knows why a request is not being send
|
||||||
var warn = function(message) {
|
var warn = function (message) {
|
||||||
if (con && con.warn) con.warn("Simple Analytics:", message);
|
if (con && con.warn) con.warn("Simple Analytics:", message);
|
||||||
};
|
};
|
||||||
|
|
||||||
var now = Date.now;
|
var now = Date.now;
|
||||||
|
|
||||||
var uuid = function() {
|
var uuid = function () {
|
||||||
var cryptoObject = window.crypto || window.msCrypto;
|
var cryptoObject = window.crypto || window.msCrypto;
|
||||||
var emptyUUID = [1e7] + -1e3 + -4e3 + -8e3 + -1e11;
|
var emptyUUID = [1e7] + -1e3 + -4e3 + -8e3 + -1e11;
|
||||||
|
|
||||||
if (!cryptoObject)
|
if (cryptoObject && cryptoObject.getRandomValues)
|
||||||
return emptyUUID.replace(/[018]/g, function(c) {
|
return emptyUUID.replace(/[018]/g, function (c) {
|
||||||
var r = (Math.random() * 16) | 0,
|
return (
|
||||||
v = c < 2 ? r : (r & 0x3) | 0x8;
|
c ^
|
||||||
return v.toString(16);
|
(cryptoObject.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
|
||||||
|
).toString(16);
|
||||||
});
|
});
|
||||||
|
|
||||||
return emptyUUID.replace(/[018]/g, function(c) {
|
return emptyUUID.replace(/[018]/g, function (c) {
|
||||||
return (
|
var r = (Math.random() * 16) | 0,
|
||||||
c ^
|
v = c < 2 ? r : (r & 0x3) | 0x8;
|
||||||
(cryptoObject.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
|
return v.toString(16);
|
||||||
).toString(16);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
var assign = function() {
|
var assign = function () {
|
||||||
var to = {};
|
var to = {};
|
||||||
for (var index = 0; index < arguments.length; index++) {
|
for (var index = 0; index < arguments.length; index++) {
|
||||||
var nextSource = arguments[index];
|
var nextSource = arguments[index];
|
||||||
@ -84,17 +89,22 @@
|
|||||||
/* Do nothing */
|
/* Do nothing */
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send data via image of XHR request
|
// Send data via image
|
||||||
function sendData(data) {
|
function sendData(data, callback) {
|
||||||
data = assign(payload, data);
|
data = assign(payload, data);
|
||||||
new Image().src =
|
var image = new Image();
|
||||||
|
if (callback) {
|
||||||
|
image.onerror = callback;
|
||||||
|
image.onload = callback;
|
||||||
|
}
|
||||||
|
image.src =
|
||||||
fullApiUrl +
|
fullApiUrl +
|
||||||
"/send.gif?" +
|
"/send.gif?" +
|
||||||
Object.keys(data)
|
Object.keys(data)
|
||||||
.filter(function(key) {
|
.filter(function (key) {
|
||||||
return data[key] != undefinedVar;
|
return data[key] != undefinedVar;
|
||||||
})
|
})
|
||||||
.map(function(key) {
|
.map(function (key) {
|
||||||
return (
|
return (
|
||||||
encodeURIComponentFunc(key) +
|
encodeURIComponentFunc(key) +
|
||||||
"=" +
|
"=" +
|
||||||
@ -111,7 +121,7 @@
|
|||||||
sendData({
|
sendData({
|
||||||
type: errorText,
|
type: errorText,
|
||||||
error: errorOrMessage,
|
error: errorOrMessage,
|
||||||
url: hostname + loc.pathname
|
url: options.hostname + loc.pathname,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -119,7 +129,7 @@
|
|||||||
// from our script (checked by filename) to our server.
|
// from our script (checked by filename) to our server.
|
||||||
addEventListenerFunc(
|
addEventListenerFunc(
|
||||||
errorText,
|
errorText,
|
||||||
function(event) {
|
function (event) {
|
||||||
if (event.filename && event.filename.indexOf(baseUrl) > -1) {
|
if (event.filename && event.filename.indexOf(baseUrl) > -1) {
|
||||||
sendError(event.message);
|
sendError(event.message);
|
||||||
}
|
}
|
||||||
@ -136,20 +146,23 @@
|
|||||||
var scrolled = 0;
|
var scrolled = 0;
|
||||||
/** endif **/
|
/** endif **/
|
||||||
|
|
||||||
|
// When a customer overwrites the hostname, we need to know what the original
|
||||||
|
// hostname was to hide that domain from referrer traffic
|
||||||
|
if (options.hostname !== hostname) payload.hostname_original = hostname;
|
||||||
|
|
||||||
// Don't track when localhost
|
// Don't track when localhost
|
||||||
/** unless testing **/
|
/** unless testing **/
|
||||||
if (loc.hostname.indexOf(".") == -1)
|
if (hostname.indexOf(".") == -1) return warn(notSending + "from " + hostname);
|
||||||
return warn(notSending + "from localhost");
|
|
||||||
/** endunless **/
|
/** endunless **/
|
||||||
|
|
||||||
try {
|
try {
|
||||||
var getParams = function(regex) {
|
var getParams = function (regex) {
|
||||||
// From the search we grab the utm_source and ref and save only that
|
// From the search we grab the utm_source and ref and save only that
|
||||||
var matches = loc.search.match(
|
var matches = loc.search.match(
|
||||||
new RegExp("[?&](" + regex + ")=([^?&]+)", "gi")
|
new RegExp("[?&](" + regex + ")=([^?&]+)", "gi")
|
||||||
);
|
);
|
||||||
var match = matches
|
var match = matches
|
||||||
? matches.map(function(m) {
|
? matches.map(function (m) {
|
||||||
return m.split("=")[1];
|
return m.split("=")[1];
|
||||||
})
|
})
|
||||||
: [];
|
: [];
|
||||||
@ -166,10 +179,12 @@
|
|||||||
source: getParams(utmRegexPrefix + "source|source|ref"),
|
source: getParams(utmRegexPrefix + "source|source|ref"),
|
||||||
medium: getParams(utmRegexPrefix + "medium"),
|
medium: getParams(utmRegexPrefix + "medium"),
|
||||||
campaign: getParams(utmRegexPrefix + "campaign"),
|
campaign: getParams(utmRegexPrefix + "campaign"),
|
||||||
|
term: getParams(utmRegexPrefix + "term"),
|
||||||
|
content: getParams(utmRegexPrefix + "content"),
|
||||||
referrer:
|
referrer:
|
||||||
(doc.referrer || "")
|
(doc.referrer || "")
|
||||||
.replace(/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/, "$4")
|
.replace(/^https?:\/\/((m|l|w{2,3}([0-9]+)?)\.)?([^?#]+)(.*)$/, "$4")
|
||||||
.replace(/^([^/]+)\/$/, "$1") || undefinedVar
|
.replace(/^([^/]+)\/$/, "$1") || undefinedVar,
|
||||||
};
|
};
|
||||||
|
|
||||||
// We don't put msHidden in if duration block, because it's used outside of that functionality
|
// We don't put msHidden in if duration block, because it's used outside of that functionality
|
||||||
@ -179,7 +194,7 @@
|
|||||||
var hiddenStart;
|
var hiddenStart;
|
||||||
window.addEventListener(
|
window.addEventListener(
|
||||||
"visibilitychange",
|
"visibilitychange",
|
||||||
function() {
|
function () {
|
||||||
if (doc.hidden) hiddenStart = now();
|
if (doc.hidden) hiddenStart = now();
|
||||||
else msHidden += now() - hiddenStart;
|
else msHidden += now() - hiddenStart;
|
||||||
},
|
},
|
||||||
@ -189,7 +204,7 @@
|
|||||||
|
|
||||||
var sendBeaconText = "sendBeacon";
|
var sendBeaconText = "sendBeacon";
|
||||||
|
|
||||||
var sendOnLeave = function(id, push) {
|
var sendOnLeave = function (id, push) {
|
||||||
var append = { type: "append", original_id: push ? id : lastPageId };
|
var append = { type: "append", original_id: push ? id : lastPageId };
|
||||||
|
|
||||||
/** if duration **/
|
/** if duration **/
|
||||||
@ -218,7 +233,7 @@
|
|||||||
var scroll = "scroll";
|
var scroll = "scroll";
|
||||||
var body = doc.body || {};
|
var body = doc.body || {};
|
||||||
var documentElement = doc.documentElement || {};
|
var documentElement = doc.documentElement || {};
|
||||||
var position = function() {
|
var position = function () {
|
||||||
try {
|
try {
|
||||||
var Height = "Height";
|
var Height = "Height";
|
||||||
var scrollHeight = scroll + Height;
|
var scrollHeight = scroll + Height;
|
||||||
@ -245,11 +260,11 @@
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
addEventListenerFunc("load", function() {
|
addEventListenerFunc("load", function () {
|
||||||
scrolled = position();
|
scrolled = position();
|
||||||
addEventListenerFunc(
|
addEventListenerFunc(
|
||||||
scroll,
|
scroll,
|
||||||
function() {
|
function () {
|
||||||
if (scrolled < position()) scrolled = position();
|
if (scrolled < position()) scrolled = position();
|
||||||
},
|
},
|
||||||
false
|
false
|
||||||
@ -257,7 +272,7 @@
|
|||||||
});
|
});
|
||||||
/** endif **/
|
/** endif **/
|
||||||
|
|
||||||
var sendPageView = function(isPushState, deleteSourceInfo) {
|
var sendPageView = function (isPushState, deleteSourceInfo) {
|
||||||
if (isPushState) sendOnLeave("" + lastPageId, true);
|
if (isPushState) sendOnLeave("" + lastPageId, true);
|
||||||
lastPageId = uuid();
|
lastPageId = uuid();
|
||||||
page.id = lastPageId;
|
page.id = lastPageId;
|
||||||
@ -267,12 +282,12 @@
|
|||||||
https: loc.protocol == https,
|
https: loc.protocol == https,
|
||||||
timezone: timezone,
|
timezone: timezone,
|
||||||
width: window.innerWidth,
|
width: window.innerWidth,
|
||||||
type: pageviewsText
|
type: pageviewsText,
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
var pageview = function(isPushState) {
|
var pageview = function (isPushState) {
|
||||||
// Obfuscate personal data in URL by dropping the search and hash
|
// Obfuscate personal data in URL by dropping the search and hash
|
||||||
var path = decodeURIComponentFunc(loc.pathname);
|
var path = decodeURIComponentFunc(loc.pathname);
|
||||||
|
|
||||||
@ -282,7 +297,7 @@
|
|||||||
lastSendPath = path;
|
lastSendPath = path;
|
||||||
|
|
||||||
var data = {
|
var data = {
|
||||||
path: path
|
path: path,
|
||||||
};
|
};
|
||||||
|
|
||||||
// If a user does refresh we need to delete the referrer because otherwise it count double
|
// If a user does refresh we need to delete the referrer because otherwise it count double
|
||||||
@ -310,7 +325,7 @@
|
|||||||
isPushState || userNavigated
|
isPushState || userNavigated
|
||||||
? false
|
? false
|
||||||
: doc.referrer
|
: doc.referrer
|
||||||
? doc.referrer.split(slash)[2] != loc.hostname
|
? doc.referrer.split(slash)[2] != hostname
|
||||||
: true;
|
: true;
|
||||||
/** endif **/
|
/** endif **/
|
||||||
|
|
||||||
@ -323,46 +338,60 @@
|
|||||||
|
|
||||||
/** if events **/
|
/** if events **/
|
||||||
var sessionId = uuid();
|
var sessionId = uuid();
|
||||||
|
var validTypes = ["string", "number"];
|
||||||
|
|
||||||
var sendEvent = function(event) {
|
var endEvent = function () {};
|
||||||
|
|
||||||
|
var sendEvent = function (event, callbackRaw) {
|
||||||
var isFunction = event instanceof Function;
|
var isFunction = event instanceof Function;
|
||||||
if (["string", "number"].indexOf(typeof event) < 0 && !isFunction)
|
var callback =
|
||||||
return warn("event is not a string: " + event);
|
callbackRaw instanceof Function ? callbackRaw : function () {};
|
||||||
|
|
||||||
|
if (validTypes.indexOf(typeof event) < 0 && !isFunction) {
|
||||||
|
warn("event is not a string: " + event);
|
||||||
|
return callback();
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (isFunction) {
|
if (isFunction) {
|
||||||
event = event();
|
event = event();
|
||||||
if (["string", "number"].indexOf(typeof event) < 0)
|
if (validTypes.indexOf(typeof event) < 0) {
|
||||||
return warn("event function output is not a string: " + event);
|
warn("event function output is not a string: " + event);
|
||||||
|
return callback();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return warn("in your event function: " + error.message);
|
warn("in your event function: " + error.message);
|
||||||
|
return callback();
|
||||||
}
|
}
|
||||||
|
|
||||||
event = ("" + event).replace(/[^a-z0-9]+/gi, "_").replace(/(^_|_$)/g, "");
|
event = ("" + event).replace(/[^a-z0-9]+/gi, "_").replace(/(^_|_$)/g, "");
|
||||||
if (event)
|
if (event)
|
||||||
sendData(
|
sendData(
|
||||||
assign(source, {
|
assign(source, {
|
||||||
type: "event",
|
type: "event",
|
||||||
event: event,
|
event: event,
|
||||||
session_id: sessionId
|
session_id: sessionId,
|
||||||
})
|
}),
|
||||||
|
callback
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
var defaultEventFunc = function(event) {
|
var defaultEventFunc = function (event, callback) {
|
||||||
sendEvent(event);
|
sendEvent(event, callback);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Set default function if user didn't define a function
|
// Set default function if user didn't define a function
|
||||||
if (!window[functionName]) window[functionName] = defaultEventFunc;
|
if (!window[options.functionName])
|
||||||
|
window[options.functionName] = defaultEventFunc;
|
||||||
|
|
||||||
var eventFunc = window[functionName];
|
var eventFunc = window[options.functionName];
|
||||||
|
|
||||||
// Read queue of the user defined function
|
// Read queue of the user defined function
|
||||||
var queue = eventFunc && eventFunc.q ? eventFunc.q : [];
|
var queue = eventFunc && eventFunc.q ? eventFunc.q : [];
|
||||||
|
|
||||||
// Overwrite user defined function
|
// Overwrite user defined function
|
||||||
window[functionName] = defaultEventFunc;
|
window[options.functionName] = defaultEventFunc;
|
||||||
|
|
||||||
// Post events from the queue of the user defined function
|
// Post events from the queue of the user defined function
|
||||||
for (var event in queue) sendEvent(queue[event]);
|
for (var event in queue) sendEvent(queue[event]);
|
||||||
|
9
assets/vendor/emoji/emoji.js
vendored
9
assets/vendor/emoji/emoji.js
vendored
@ -4,14 +4,7 @@
|
|||||||
https://github.com/twitter/twemoji/blob/gh-pages/LICENSE
|
https://github.com/twitter/twemoji/blob/gh-pages/LICENSE
|
||||||
*/
|
*/
|
||||||
|
|
||||||
(function (
|
(function () {
|
||||||
|
|
||||||
// WARNING: this file is generated automatically via
|
|
||||||
// `node scripts/build.js`
|
|
||||||
// please update its `createTwemoji` function
|
|
||||||
// at the bottom of the same file instead.
|
|
||||||
|
|
||||||
) {
|
|
||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
/* jshint maxparams:4 */
|
/* jshint maxparams:4 */
|
||||||
|
@ -44,11 +44,11 @@ A _very_ barebones example is embedded above ([view the source here](https://git
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Minified JS: (392 bytes gzipped 📦)
|
### Minified JS: (410 bytes gzipped 📦)
|
||||||
|
|
||||||
```js
|
```js
|
||||||
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
|
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
|
||||||
(function(){var e=window,t=e.document,i=t.body.classList,a=localStorage,c="dark_mode_pref",d=a.getItem(c),r="dark",o="light",s=t.querySelector(".dark-mode-toggle"),n=!1,m=function(e){i.remove(r,o);i.add(e);n=e===r};d===r&&m(r);d===o&&m(o);if(!d){var l="(prefers-color-scheme: dark)",f="(prefers-color-scheme: light)";e.matchMedia(l).matches?m(r):m(o);e.matchMedia(l).addListener((function(e){e.matches&&m(r)}));e.matchMedia(f).addListener((function(e){e.matches&&m(o)}))}if(s){s.style.visibility="visible";s.addEventListener("click",(function(){if(n){m(o);a.setItem(c,o)}else{m(r);a.setItem(c,r)}}),!0)}})();
|
(function(){var e=window,t=e.document,i=t.body.classList,a=localStorage,c="dark_mode_pref",d=a.getItem(c),n="dark",o="light",r=o,s=t.querySelector(".dark-mode-toggle"),m=r===n,l=function(e){i.remove(n,o);i.add(e);m=e===n};d===n&&l(n);d===o&&l(o);if(!d){var f=function(e){return"(prefers-color-scheme: "+e+")"};e.matchMedia(f(n)).matches?l(n):e.matchMedia(f(o)).matches?l(o):l(r);e.matchMedia(f(n)).addListener((function(e){e.matches&&l(n)}));e.matchMedia(f(o)).addListener((function(e){e.matches&&l(o)}))}if(s){s.style.visibility="visible";s.addEventListener("click",(function(){if(m){l(o);a.setItem(c,o)}else{l(n);a.setItem(c,n)}}),!0)}})();
|
||||||
```
|
```
|
||||||
|
|
||||||
### Full JS:
|
### Full JS:
|
||||||
@ -56,32 +56,35 @@ A _very_ barebones example is embedded above ([view the source here](https://git
|
|||||||
```js
|
```js
|
||||||
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
|
/*! Dark mode switcheroo | MIT License | jrvs.io/darkmode */
|
||||||
|
|
||||||
(function() {
|
(function () {
|
||||||
// improve variable mangling when minifying
|
// improve variable mangling when minifying
|
||||||
var win = window;
|
var win = window;
|
||||||
var doc = win.document;
|
var doc = win.document;
|
||||||
var bod = doc.body;
|
var body = doc.body;
|
||||||
var cls = bod.classList;
|
var classes = body.classList;
|
||||||
var sto = localStorage;
|
var storage = localStorage;
|
||||||
|
|
||||||
// check for preset `dark_mode_pref` preference in localStorage
|
// check for preset `dark_mode_pref` preference in local storage
|
||||||
var pref_key = 'dark_mode_pref';
|
var pref_key = 'dark_mode_pref';
|
||||||
var pref = sto.getItem(pref_key);
|
var pref = storage.getItem(pref_key);
|
||||||
|
|
||||||
// change CSS via these <body> classes:
|
// change CSS via these <body> classes:
|
||||||
var dark = 'dark';
|
var dark = 'dark';
|
||||||
var light = 'light';
|
var light = 'light';
|
||||||
|
|
||||||
|
// which class is <body> set to initially?
|
||||||
|
var default_theme = light;
|
||||||
|
|
||||||
// use an element with class `dark-mode-toggle` to trigger swap when clicked
|
// use an element with class `dark-mode-toggle` to trigger swap when clicked
|
||||||
var toggle = doc.querySelector('.dark-mode-toggle');
|
var toggle = doc.querySelector('.dark-mode-toggle');
|
||||||
|
|
||||||
// keep track of current state (light by default) no matter how we got there
|
// keep track of current state no matter how we got there
|
||||||
var active = false;
|
var active = (default_theme === dark);
|
||||||
|
|
||||||
// receives a class name and switches <body> to it
|
// receives a class name and switches <body> to it
|
||||||
var activateTheme = function(theme) {
|
var activateTheme = function (theme) {
|
||||||
cls.remove(dark, light);
|
classes.remove(dark, light);
|
||||||
cls.add(theme);
|
classes.add(theme);
|
||||||
active = (theme === dark);
|
active = (theme === dark);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -91,18 +94,23 @@ A _very_ barebones example is embedded above ([view the source here](https://git
|
|||||||
|
|
||||||
// user has never clicked the button, so go by their OS preference until/if they do so
|
// user has never clicked the button, so go by their OS preference until/if they do so
|
||||||
if (!pref) {
|
if (!pref) {
|
||||||
// check for OS dark mode setting and switch accordingly
|
// returns media query selector syntax
|
||||||
var prefers_dark = '(prefers-color-scheme: dark)';
|
var prefers = function (theme) {
|
||||||
var prefers_light = '(prefers-color-scheme: light)';
|
return '(prefers-color-scheme: ' + theme + ')';
|
||||||
|
};
|
||||||
|
|
||||||
if (win.matchMedia(prefers_dark).matches)
|
// check for OS dark/light mode preference and switch accordingly
|
||||||
|
// default to `default_theme` set above if unsupported
|
||||||
|
if (win.matchMedia(prefers(dark)).matches)
|
||||||
activateTheme(dark);
|
activateTheme(dark);
|
||||||
else
|
else if (win.matchMedia(prefers(light)).matches)
|
||||||
activateTheme(light);
|
activateTheme(light);
|
||||||
|
else
|
||||||
|
activateTheme(default_theme);
|
||||||
|
|
||||||
// real-time switching if supported by OS/browser
|
// real-time switching if supported by OS/browser
|
||||||
win.matchMedia(prefers_dark).addListener(function(e) { if (e.matches) activateTheme(dark); });
|
win.matchMedia(prefers(dark)).addListener(function (e) { if (e.matches) activateTheme(dark); });
|
||||||
win.matchMedia(prefers_light).addListener(function(e) { if (e.matches) activateTheme(light); });
|
win.matchMedia(prefers(light)).addListener(function (e) { if (e.matches) activateTheme(light); });
|
||||||
}
|
}
|
||||||
|
|
||||||
// don't freak out if page happens not to have a toggle
|
// don't freak out if page happens not to have a toggle
|
||||||
@ -111,14 +119,14 @@ A _very_ barebones example is embedded above ([view the source here](https://git
|
|||||||
toggle.style.visibility = 'visible';
|
toggle.style.visibility = 'visible';
|
||||||
|
|
||||||
// handle toggle click
|
// handle toggle click
|
||||||
toggle.addEventListener('click', function() {
|
toggle.addEventListener('click', function () {
|
||||||
// switch to the opposite theme & save preference in local storage
|
// switch to the opposite theme & save preference in local storage
|
||||||
if (!active) {
|
if (active) {
|
||||||
activateTheme(dark);
|
|
||||||
sto.setItem(pref_key, dark);
|
|
||||||
} else {
|
|
||||||
activateTheme(light);
|
activateTheme(light);
|
||||||
sto.setItem(pref_key, light);
|
storage.setItem(pref_key, light);
|
||||||
|
} else {
|
||||||
|
activateTheme(dark);
|
||||||
|
storage.setItem(pref_key, dark);
|
||||||
}
|
}
|
||||||
}, true);
|
}, true);
|
||||||
}
|
}
|
||||||
|
@ -19,4 +19,4 @@ This website uses [**Simple Analytics**](https://simpleanalytics.com/?ref=jarv.i
|
|||||||
|
|
||||||
**📈 Stats for this site are public! [View them here.](/stats/)**
|
**📈 Stats for this site are public! [View them here.](/stats/)**
|
||||||
|
|
||||||
Pages and first-party assets on this website are served by [**Netlify**](https://www.netlify.com/). Refer to their [privacy policy](https://www.netlify.com/privacy/) and [GDPR statement](https://www.netlify.com/privacy/) for more information.
|
Pages and first-party assets on this website are served by [**Netlify**](https://www.netlify.com/). Refer to their [privacy policy](https://www.netlify.com/privacy/) and [GDPR statement](https://www.netlify.com/gdpr/) for more information.
|
||||||
|
Loading…
x
Reference in New Issue
Block a user