Skip to content

Commit

Permalink
Switch to modern syntax in copy.js
Browse files Browse the repository at this point in the history
  • Loading branch information
ntsim committed Oct 28, 2024
1 parent ce83385 commit cb27efd
Showing 1 changed file with 31 additions and 34 deletions.
65 changes: 31 additions & 34 deletions source/javascripts/copy.js
Original file line number Diff line number Diff line change
@@ -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();
});
})();

0 comments on commit cb27efd

Please sign in to comment.