Okay, firstly I need to own up to having no JavaScript coding experience. So I am going cap in hand for some help on this please.
I would like the user of a webpage to be able to click on a value contained within a table (‘td’) and for it to be copied to the clipboard. So that the user knows that this has happened, I’d like a message to appear briefly letting them know that they have copied something and what that was.
Hopefully this makes sense?
I have found the following code (apologies for not remembering where) which copies the value to the clipboard okay, but this is where I am stuck and cannot get the tooltip part going.
Hoping that somebody can enlighten me!
Code Snippet
function copy(event) {
console.log("Triggered")
var target = event.target || event.srcElement;
console.log("Targeted", target)
var copyText = target.innerText || target.textContent;
navigator.clipboard.writeText(copyText)
// select the cell
var range = document.createRange();
range.selectNode(target);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
document.querySelectorAll("td")
.forEach(elem => elem.addEventListener("click", copy))
td {
border: thin solid gray;
padding: 0.2rem;
}
<table>
<tr><td>A1</td><td>A2</td><td>A3</td></tr>
<tr><td>B1</td><td>B2</td><td>B3</td></tr>
<tr><td>C1</td><td>C2</td><td>C3</td></tr>
</table>
2
Answers
After painstakingly going through my code, I found out that one bit of CSS was causing the issue and making the tooltip not show.
I am using bootstrap and the solution to make it work as per Konrad's excellent solution is to add
to the tooltip CSS.
I also changed a couple of other lines of CSS which seems to make it even better
Thanks again, Konrad!