I have an address written over multiple lines with paragraphs:
<p>Address line 1</p>
<p>Address line 2</p>
<p>Address line 3</p>
<p>County</p>
<p>Post code</p>
I want to make it possible for a user to click on any of the paragraphs to copy the text to their clipboard. If possible I would also like a small "click to copy" message to appear when hovering over the address.
I have tried wrapping the paragraphs in a button that calls a function when clicked.
<button onclick="copyText()">
<p class="copy">Address line 1</p>
<p class="copy">Address line 2</p>
<p class="copy">Address line 3</p>
<p class="copy">County</p>
<p class="copy">Post code</p>
</button>
The function in JS is written as:
function copyText(){
var copyText = document.getElementsByClass("copy");
let text = "";
for (let i = 0; i < copyText.length; i++) {
text += copyText[i] + "<br>";
}
// Select the text field
text.select();
text.setSelectionRange(0, 99999); // For mobile devices
// Copy the text inside the text field
navigator.clipboard.writeText(text.value);
// Alert the copied text
alert("Copied the text: " + text.value);
}
2
Answers
<p>
can’t go inside<button>
but<span>
is valid. You can read up more on that hereAlso,
getElementsByClass()
is invalid. It should begetElementsByClassName()
. The console in your browser’s developer tools should be telling you that.To get a message to show on hover, you can make use of a the title attribute.
So, change your HTML to something like:
And then use css to style the spans as
display: block;
if you want each element of the address to be on a new line.And change this line in your JS:
Then,
copyText
does not have the text of the button itself. It’s contained in thecontentText
orinnerText
property. You can read up more on that hereIt’s unclear what you’re trying to do here but it’s invalid because
text
is a variable, not a thing you can called functions like.select()
on.I just commented the above out because you don’t need it to meet your described objective.
To get the content you’re looking for, simply use
text
and nottext.value
. So, for example:For a quick and dirty solution I suggest you wrap in DIV element instead of BUTTON element. You can then pass "this" to copyText function to pass DIV context where you can simply pull innerText property of DIV.
For eg.
For your hover message I suggest you simply add TITLE attribute as per below.
Hope helps