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:
JavaScript
x
2
1
"A certain quote" (Author Name).
2
This is the current script to copy one div.
JavaScript
1
7
1
function copyToClipboard(element) {
2
var $temp = $("<input>");
3
$("body").append($temp);
4
$temp.val($(element).text()).select();
5
document.execCommand("copy");
6
$temp.remove();
7
}
JavaScript
1
10
10
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="divA">
3
<p>A certain quote</p>
4
</div>
5
6
<div id="divB">
7
<p>Author Name</p>
8
</div>
9
10
<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
:
JavaScript
1
14
14
1
let $divA = $('#divA');
2
let $divB = $('#divB');
3
4
$('button').on('click', e => {
5
copyToClipboard(`"${$divA.text().trim()}" (${$divB.text().trim()}).`);
6
});
7
8
function copyToClipboard(text) {
9
var $temp = $("<input>");
10
$("body").append($temp);
11
$temp.val(text).select();
12
document.execCommand("copy");
13
$temp.remove();
14
}
JavaScript
1
4
1
textarea {
2
width: 300px;
3
height: 30px;
4
}
JavaScript
1
11
11
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
2
<div id="divA">
3
<p>A certain quote</p>
4
</div>
5
<div id="divB">
6
<p>Author Name</p>
7
</div>
8
<button type="button">Copy</button><br /><br />
9
10
Paste here to test:<br />
11
<textarea></textarea>