From cb27efd9a571f7b3863e2b253ac4c0223378e4d6 Mon Sep 17 00:00:00 2001 From: Nicholas Tsim Date: Mon, 28 Oct 2024 16:01:46 +0000 Subject: [PATCH] Switch to modern syntax in copy.js --- source/javascripts/copy.js | 65 ++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 34 deletions(-) diff --git a/source/javascripts/copy.js b/source/javascripts/copy.js index 091a696..0c7b180 100644 --- a/source/javascripts/copy.js +++ b/source/javascripts/copy.js @@ -1,48 +1,45 @@ -(function () { - function Copy($module) { - this.$module = $module - } - - Copy.prototype.init = function () { - var $module = this.$module - - if (!$module) { - return +(() => { + class Copy { + constructor($module) { + this.$module = $module } - // Bail if no clipboard support (e.g. IE11) - if (!navigator.clipboard) { - return; - } + init() { + // Bail if no clipboard support (e.g. IE11) + if (!navigator.clipboard) { + return; + } - var $button = document.createElement('button') - $button.className = 'app-copy-button js-copy-button' - $button.setAttribute('aria-live', 'assertive') - $button.textContent = 'Copy code' + const $button = document.createElement('button'); - $module.insertAdjacentElement('beforebegin', $button) + $button.className = 'app-copy-button js-copy-button'; + $button.setAttribute('aria-live', 'assertive'); + $button.textContent = 'Copy code'; - $button.addEventListener('click', this.handleCopy) - } + this.$module.insertAdjacentElement('beforebegin', $button); + + $button.addEventListener('click', this.handleCopy); + } - Copy.prototype.handleCopy = function (event) { - var target = event.target.nextElementSibling; + handleCopy(event){ + const target = event.target.nextElementSibling; - navigator.clipboard.writeText(target.textContent) - .then(function () { - event.target.textContent = 'Code copied'; + navigator.clipboard.writeText(target.textContent) + .then(() => { + event.target.textContent = 'Code copied'; - setTimeout(function () { - event.target.textContent = 'Copy code'; - }, 5000); - }) - .catch(function (err) { - console.error(err); - }) + setTimeout(() => { + event.target.textContent = 'Copy code'; + }, 5000); + }) + .catch((err) => { + console.error(err); + }) + } } document.querySelectorAll('pre.highlight') - .forEach(function ($el) { + .forEach(($el) => { new Copy($el).init(); }); })();