From 2e5696f7673fde1088deca72dfb03b69cc8516e3 Mon Sep 17 00:00:00 2001 From: Filip Rojek Date: Tue, 15 Oct 2024 11:11:08 +0200 Subject: [PATCH] Added: copy text button --- sass/project.scss | 14 ++++++++++++++ static/js/code-copy.js | 30 ++++++++++++++++++++++++++++++ templates/base.html | 3 +++ templates/post.html | 5 +++++ 4 files changed, 52 insertions(+) create mode 100644 static/js/code-copy.js diff --git a/sass/project.scss b/sass/project.scss index 95b0931..d050718 100644 --- a/sass/project.scss +++ b/sass/project.scss @@ -36,6 +36,20 @@ margin: 2rem 0; } +.copy-code-wrapper { + position: relative; +} + +.copy-code { + position: absolute; + top: .5rem; + right: .5rem; + cursor: pointer; + background-color: #1b1f26; + padding: .3rem ; + border-radius: 5px; +} + @media (max-width: 768px) { .project-wrapper { max-width: 100%; diff --git a/static/js/code-copy.js b/static/js/code-copy.js new file mode 100644 index 0000000..ba7c39e --- /dev/null +++ b/static/js/code-copy.js @@ -0,0 +1,30 @@ +let codes = document.querySelectorAll("pre") + +codes.forEach(code => { + const elWrapper = document.createElement("div") + elWrapper.classList.add("copy-code-wrapper") + + + const el = document.createElement("span") + el.textContent = "Copy" + el.classList.add("copy-code") + + elWrapper.appendChild(el) + + code.parentNode.insertBefore(elWrapper, code) + + let textContent = "" + code.childNodes.forEach(child => { + textContent += child.textContent; + }) + + elWrapper.addEventListener("click", (e) => { + e.preventDefault() + navigator.clipboard.writeText(textContent) + el.textContent = "Copied!" + setTimeout(() => { + el.textContent = "Copy" + }, 5000); + }) +}) + diff --git a/templates/base.html b/templates/base.html index 88fb0df..3728069 100644 --- a/templates/base.html +++ b/templates/base.html @@ -67,6 +67,9 @@ + + {% block scripts %} + {% endblock scripts %} diff --git a/templates/post.html b/templates/post.html index a220938..7c3bff0 100644 --- a/templates/post.html +++ b/templates/post.html @@ -4,6 +4,11 @@ {% endblock styles %} +{% block scripts %} + +{% endblock scripts %} + + {% block content %}