I am using the following script to copy a div to clipboard. But I am trying to copy multiple divs (DivA + DivB) with the same button, while adding some quotes and brackets around each div. I saw some answers (like this one, and this), but I can’t seem to be able to implement them to the current script.
So the output should be like:
"A certain quote" (Author Name).
This is the current script to copy one div.
function copyToClipboard(element) { var $temp = $("<input>"); $("body").append($temp); $temp.val($(element).text()).select(); document.execCommand("copy"); $temp.remove(); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="divA"> <p>A certain quote</p> </div> <div id="divB"> <p>Author Name</p> </div> <button onclick="copyToClipboard('#divA')">Copy</button>
Advertisement
Answer
The issue is because you’re only reading the text from ‘#divA’, as that’s the selector passed to the copyToClipboard()
function.
To do what you require amend the logic to create a string in the format you require containing the text of both #divA
and #divB
:
let $divA = $('#divA'); let $divB = $('#divB'); $('button').on('click', e => { copyToClipboard(`"${$divA.text().trim()}" (${$divB.text().trim()}).`); }); function copyToClipboard(text) { var $temp = $("<input>"); $("body").append($temp); $temp.val(text).select(); document.execCommand("copy"); $temp.remove(); }
textarea { width: 300px; height: 30px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="divA"> <p>A certain quote</p> </div> <div id="divB"> <p>Author Name</p> </div> <button type="button">Copy</button><br /><br /> Paste here to test:<br /> <textarea></textarea>