JSFiddle - React, Tailwind, and code Playground
by thanhansoft
HTML
<br><br><br><br><br>
<div>
<h1 class="copy-btn tooltip" data-copy="This is the text to be copied." data-text="Copy Text 1 Tooltip">
Copy Text 1 asdasdasd
</h1>
<button class="copy-btn tooltip" data-copy="This is the text to be copied." data-text="Copy Text 1 Tooltip">
Copy Text 1
</button>
<button class="copy-btn tooltip" data-copy="Another text to be copied." data-text="Copy Text 2 Tooltip">
Copy Text 2
</button>
<button class="copy-btn tooltip" data-copy="Yet another text to be copied." data-text="Copy Text 3 Tooltip">
Copy Text 3
</button>
</div>
CSS
.tooltip {
position: relative;
display: inline-block;
cursor: pointer;
}
/* Tooltip text */
.tooltip .tooltiptext {
visibility: hidden;
width: auto;
font-size: 1rem;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 5px;
padding: 5px;
position: absolute;
z-index: 1;
bottom: 150%; /* Position the tooltip above the text */
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.3s;
}
/* Tooltip arrow */
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%; /* At the bottom of the tooltip */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
JavaScript
document.addEventListener('DOMContentLoaded', function() {
const copyButtons = document.querySelectorAll('.copy-btn');
copyButtons.forEach(button => {
// Create tooltip element dynamically
const tooltipText = button.getAttribute('data-text');
const tooltipSpan = document.createElement('span');
tooltipSpan.className = 'tooltiptext';
tooltipSpan.innerText = tooltipText;
button.appendChild(tooltipSpan);
// Add click event listener for copying text
button.addEventListener('click', function() {
const textToCopy = this.getAttribute('data-copy');
copyToClipboard(textToCopy);
});
});
});
function copyToClipboard(text) {
const textArea = document.createElement('textarea');
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
document.execCommand('copy');
document.body.removeChild(textArea);
alert('Copied to clipboard: ' + text);
}