In the table, I am trying to create an Onclick text copier with a copied text tooltip message. Actually, I have done successfully creating an individual id text copier but I am facing a problem with the individual tooltip message, it’s not working for not creating individual dynamic id that’s why. So how can I fix this problem for creating a custom-tooltip dynamic id?
function textCopied(that){ var inp =document.createElement('input'); document.body.appendChild(inp) inp.value =that.textContent inp.select(); document.execCommand('copy',false); inp.remove(); document.getElementById("custom-tooltip").style.display = "inline"; setTimeout( function() { document.getElementById("custom-tooltip").style.display = "none"; }, 1000); };
.container { display: flex; justify-content: center; height: 100vh; } .copybutton{ background-color: #fff; border: 0; outline: 0; cursor: pointer; opacity: 1; position: absolute; width: 40px; height: 40px; z-index: 9; border-radius: 24px; } .button-tooltip-container { display: flex; align-items: center; margin-top: 16px; min-height: 30px; } #custom-tooltip { position: absolute; display: none; margin-left: 40px; padding: 5px 12px; background-color: #000000df; border-radius: 4px; color: #fff; } table tbody tr td{ padding: 5px 40px; }
<div class="container"> <table> <thaed> <tr> <th>ID</th> </tr> </thaed> <tbody> <tr> <td> <div class="button-tooltip-container"> <span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94426</span> <span id="custom-tooltip">copied!</span> </div> </td> </tr> <tr> <td> <div class="button-tooltip-container"> <span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94425</span> <span id="custom-tooltip">copied!</span> </div> </td> </tr> <tr> <td> <div class="button-tooltip-container"> <span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94424</span> <span id="custom-tooltip">copied!</span> </div> </td> </tr> </tbody> </table> </div>
Advertisement
Answer
I would suggest that you change “#custom-tooltip” to a class, “.custom-tooltip”, and then search by proximity to the clicked element the correct tooltip to display, like so:
function textCopied(el){ var inp =document.createElement('input'); document.body.appendChild(inp); inp.value = el.textContent; inp.select(); document.execCommand('copy',false); inp.remove(); var tt = el.parentNode.querySelector(".custom-tooltip"); tt.style.display = "inline"; setTimeout( function() { tt.style.display = "none"; }, 1000); };