Merge pull request #3630 from alphagov/fix-copy-to-clipboard-selection

Fix copy to clipboard selection
This commit is contained in:
Tom Byers
2020-09-16 15:40:03 +01:00
committed by GitHub
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();