I’m looking a a simple solution:
- I just have a text (it can be a button without borders or paragraph or span, but no input field)
- I want to be able to just click on text and to be copied to clipboard (in all common web browsers)
- without any additional buttons
- after clicking display a tooltip.
I saw many articles but based on input field.
I also tried to use this code: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_copy_clipboard2
It looks very nice with tooltip but there is the additional button and it is based on input field.
How to do this, using only one text field (it can be a button without borders or paragraph or span, but no input field) ?
3
Answers
Try the following Code:
Using a button we’re calling our function
myFunction
once the button is clicked. In our function we copy the value we gave our button, in this case "Copied text" and alert the user, that the text was copied.The main reason why you’ve struggled to follow this is becuase of the first few lines in the code (which is specific to
input
tags).But you can adapt the remaining code like so:
(Adapted from the W3 Link
I believe the bit that causes you some issue is
Which I believe is to help some mobile browsers to grab the
value
from the input, but since you want a different element type (in my example:<p>...</p>
), I don’t believe it is needed…In the below snippet:
#myTarget
innerText
innerHTML
You can assign both listeners to a normal element, it doesn’t need to be a button.
Starting from the w3schools example:
See codepen preview