Make copy to clipboard work with prefixes

The prefix was being included in the selection
copied.
This commit is contained in:
Tom Byers
2020-09-15 12:53:58 +01:00
parent c2e737b323
commit 956f5d4c3e
3 changed files with 52 additions and 9 deletions

View File

@@ -27,11 +27,27 @@
`
};
this.getRangeFromElement = function (keyElement) {
const range = document.createRange();
let prefixIndex = -1;
Array.from(keyElement.childNodes).forEach((el, idx) => {
if ((el.nodeType === 1) && el.classList.contains('govuk-visually-hidden')) {
prefixIndex = idx;
}
});
range.selectNodeContents(keyElement);
if (prefixIndex !== -1) { range.setStart(keyElement, prefixIndex + 1); }
return range;
};
this.copyKey = function(keyElement, callback) {
var selection = window.getSelection ? window.getSelection() : document.selection,
range = document.createRange();
range = this.getRangeFromElement(keyElement);
selection.removeAllRanges();
range.selectNodeContents(keyElement);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();