Search code examples
javascriptclipboarddata

How to copy the background-color of a div element to the clipboard on click?


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.


Solution

  • 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);