Basically, the title. I have 4 divs that represent the main 4 colors of something, they are dynamically displayed, so they will be different. What I want do with them, is to copy the background-color (in HEX) to the clipboard when you click on it, and display a message that will say "Copied!" and it will fade out after 1.5s.
Asked
Active
Viewed 1,374 times
1
-
1You are being downvoted because the people here don't like "do my homework for me" type questions. If you include some HTML and Javascript code of what you've tried, you will have a much better chance of getting a good answer! – Jaap Joris Vens Jan 13 '21 at 22:18
-
1heh yeah, but since they're a new contributor I let it pass – Love2Code Jan 13 '21 at 22:24
-
2Yes, you are right hedgie, I didn't even read my question when I posted it, it sounded like I was demanding something to be done, without even saying thank you. So sorry for that; in any case I already solved it adding an span in the element with the HEX code and copying it to the clipboard – Miguel Jan 13 '21 at 23:28
2 Answers
1
First of all let's assume the div
has an id test
, so we can get the element.
const el = document.getElementById('test');
You might want to get it using class name, tag name, etc but it's all up to you.
Then we get computed background colour:
let bgColor = window.getComputedStyle(el).backgroundColor;
Now we need to create a text. Then select the text and copy it to clipboard:
let text = document.createElement('textarea');
// We don't want to see it on the page but only use it as a text holder for the moment
text.style.display = 'none';
// Append to document
document.body.appendChild(text);
// Set the background colour to it
text.value = bgColor;
// Select the text
text.select();
// Copy the text we just selected
document.execCommand('copy');
// Remove the textarea we just created
document.body.removeChild(text);

noob
- 480
- 3
- 20
-
-
Thank you noob for this code, but in the end I ended up adding an span inside the DIV with the HEX color as text and copying it from there. I will mark it as solved because it works for the main question I did, with a little tweaks. – Miguel Jan 13 '21 at 23:33
0
I would recommend that you show what you have tried or at least what your code looks like. You can use the .execCommand() method in javascript (or something similar) to achieve this. You would most likely find this link helpful. https://alligator.io/js/copying-to-clipboard/

Love2Code
- 440
- 6
- 19
-
1Yes, I was lazy and I didn't read my question, sorry if it sounded like I was doing a demand, thanks for your help too, it served me well to think of a solution – Miguel Jan 13 '21 at 23:30