0

I have this simple function that allows you to click any table cell and it copies the data to the clipboard. The cell will also blink red to let you know it was copied. This works fine, but you'll notice there's an input tag in each cell (all the similar examples I found also used inputs or some other form tags) I don't need inputs because the data in my cells isn't going to change. Is there a way to do this without input tags. Would the data in a normal table cell be innerHTML Can that be copied onclick? No jQuery please.

function myFunction(itemid) {
  var copyText = document.getElementById(itemid);
  copyText.select();
  document.execCommand("Copy");
  // blink red
  document.getElementById(itemid).style.backgroundColor="#FF0000";
  setTimeout(function(){document.getElementById(itemid).style.backgroundColor="#FFFFFF";},300);
}
::selection {background:none;}
input {outline:0;cursor:pointer}
<table>
<td><input type="text" value="Cheese" id="cell1" onclick="myFunction('cell1')"></td>
<td><input type="text" value="Crackers" id="cell2" onclick="myFunction('cell2')"></td><tr>

<td><input type="text" value="Milk" id="cell3" onclick="myFunction('cell3')"></td>
<td><input type="text" value="Bread" id="cell4" onclick="myFunction('cell4')"></td>
</table>

1 Answer 1

1

try this, the animation is up to you

        let table = document.getElementById('tableId');

    table.addEventListener('click', (e) => {
        let target = e.target;
        if(target.localName === 'td') {
            let range = document.createRange();
            range.selectNodeContents(target);  
            let sel= document.getSelection(); 
            sel.removeAllRanges(); 
            sel.addRange(range); 

            document.execCommand('copy');
            sel.removeAllRanges();
            target.classList.add('copy-animate');
            setTimeout(() => {
                target.classList.remove('copy-animate');
            }, 200);
        }
    });
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you, but it's not working, what am I doing wrong. I'm not experienced with javascript.... here's the code...
Ooops, I'm not sure how to show my code in a comment
Uncaught TypeError: Cannot read property 'addEventListener' of null
Did you add the table element an id=tableId ?
Yeah, I did that. I'm sure I'm doing something stupid. Hold on, I'll add mine to your code post...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.