I've got a fairly straightforward requirement to implement - a button on a webpage which will copy a block of text with an image in it to the clipboard.
I do know how to copy text and I know how to copy an image. As far as I can tell, I can't do both. Am I missing something or is it indeed not possible with JavaScript? Can anyone think of any alternative solution (I'd say Flash it it was 1995 :-) ).
Thanks a lot
CodePudding user response:
You can do this by combining the execCommand
and Range/Selection
functionality:
let button = document.querySelector('#copy-button');
button.addEventListener('click', function () {
let selection = window.getSelection();
let container = document.querySelector('.container');
if (selection.rangeCount > 0) {
selection.removeAllRanges();
}
const range = document.createRange();
range.selectNode(container);
selection.addRange(range);
document.execCommand("copy");
selection.removeAllRanges();
});
.container {
position: relative;
text-align: center;
color: white;
}
.bottom-left {
position: absolute;
bottom: 8px;
left: 16px;
}
.top-left {
position: absolute;
top: 8px;
left: 16px;
}
.top-right {
position: absolute;
top: 8px;
right: 16px;
}
.bottom-right {
position: absolute;
bottom: 8px;
right: 16px;
}
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
<button id="copy-button">copy</button>
<div class="container">
<img src="https://moview.nl/wp-content/uploads/2018/04/Mountain_RvB-3-bw.jpg" alt="Snow" style="width:100%;">
<div class="bottom-left">Bottom Left</div>
<div class="top-left">Top Left</div>
<div class="top-right">Top Right</div>
<div class="bottom-right">Bottom Right</div>
<div class="centered">Centered</div>
</div>