website/assets/script/inline-code.js

92 lines
2.6 KiB
JavaScript
Raw Normal View History

2022-07-10 10:20:04 +01:00
window.addEventListener("load", function() {
// Get list of inline code elements
var codes = document.getElementsByClassName("inline-code");
for (var i = 0; i < codes.length; i++) {
var code = codes[i];
2022-11-03 20:05:54 +00:00
var input = code.getElementsByTagName("input")[0];
2022-07-10 10:20:04 +01:00
// Select all in input when clicked
2022-11-03 20:05:54 +00:00
input.onclick = function(e) {
var event = e || window.event;
var target = event.target || event.srcElement;
inputSelectAll(target);
2022-07-10 10:20:04 +01:00
}
// Add clipboard icon
// TODO doesn't work on IE8 and below
var themes = ["dark", "light"];
for (var j = 0; j < themes.length; j++) {
var base = "/assets/icons/" + themes[j] + "-mode/";
var svg = document.createElement("source");
svg.type = "image/svg+xml";
svg.srcset = base + "copy.svg";
//var img = document.createElement("img");
var img = new Image();
img.style.zIndex = "3";
img.className = "inline-code-icon inline-code-icon-end " + themes[j];
img.setAttribute("data-theme", themes[j]);
img.src = base + "copy.png";
img.alt = "Clipboard Icon";
img.title = "Copy to clipboard";
2022-11-03 20:05:54 +00:00
img.onclick = function(e) {
var event = e || window.event;
var target = event.target || event.srcElement;
2022-07-10 10:20:04 +01:00
copyInputText(
2022-11-03 20:05:54 +00:00
target.parentElement.parentElement.getElementsByTagName('input')[0],
target,
target.getAttribute("data-theme")
2022-07-10 10:20:04 +01:00
);
};
var picture = document.createElement("picture");
picture.appendChild(svg);
picture.appendChild(img);
code.appendChild(picture);
}
}
}, false);
function copyInputText(input, clipboardIcon, theme) {
2022-11-03 20:05:54 +00:00
inputSelectAll(input);
2022-07-10 10:20:04 +01:00
2022-11-03 20:05:54 +00:00
var path;
if (document.execCommand("copy")) {
path = "/assets/icons/" + theme + "-mode/";
} else {
console.log("no"); // TODO X icon
}
2022-07-10 10:20:04 +01:00
clipboardIcon.src = path + "check.svg";
2022-11-03 20:05:54 +00:00
clipboardIcon.previousSibling.srcset = path + "check.png";
2022-07-10 10:20:04 +01:00
2022-11-03 20:05:54 +00:00
inputDeselect(input);
2022-07-10 10:20:04 +01:00
2022-11-03 20:05:54 +00:00
setTimeout(function() {
2022-07-10 10:20:04 +01:00
clipboardIcon.src = path + "copy.svg";
2022-11-03 20:05:54 +00:00
clipboardIcon.previousSibling.srcset = path + "copy.png";
2022-07-10 10:20:04 +01:00
}, 1000);
}
function inputSelectAll(input) {
input.focus();
if (input.select) input.select();
else input.setSelectionRange(0, this.value.length);
}
2022-11-03 20:05:54 +00:00
function inputDeselect(input) {
if (input.blur) input.blur();
else input.setSelectionRange(0, 0);
}