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?
JavaScript
x
13
13
1
function textCopied(that){
2
var inp =document.createElement('input');
3
document.body.appendChild(inp)
4
inp.value =that.textContent
5
inp.select();
6
document.execCommand('copy',false);
7
inp.remove();
8
9
document.getElementById("custom-tooltip").style.display = "inline";
10
setTimeout( function() {
11
document.getElementById("custom-tooltip").style.display = "none";
12
}, 1000);
13
};
JavaScript
1
35
35
1
.container {
2
display: flex;
3
justify-content: center;
4
height: 100vh;
5
}
6
.copybutton{
7
background-color: #fff;
8
border: 0;
9
outline: 0;
10
cursor: pointer;
11
opacity: 1;
12
position: absolute;
13
width: 40px;
14
height: 40px;
15
z-index: 9;
16
border-radius: 24px;
17
}
18
.button-tooltip-container {
19
display: flex;
20
align-items: center;
21
margin-top: 16px;
22
min-height: 30px;
23
}
24
#custom-tooltip {
25
position: absolute;
26
display: none;
27
margin-left: 40px;
28
padding: 5px 12px;
29
background-color: #000000df;
30
border-radius: 4px;
31
color: #fff;
32
}
33
table tbody tr td{
34
padding: 5px 40px;
35
}
JavaScript
1
35
35
1
<div class="container">
2
<table>
3
<thaed>
4
<tr>
5
<th>ID</th>
6
</tr>
7
</thaed>
8
<tbody>
9
<tr>
10
<td>
11
<div class="button-tooltip-container">
12
<span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94426</span>
13
<span id="custom-tooltip">copied!</span>
14
</div>
15
</td>
16
</tr>
17
<tr>
18
<td>
19
<div class="button-tooltip-container">
20
<span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94425</span>
21
<span id="custom-tooltip">copied!</span>
22
</div>
23
</td>
24
</tr>
25
<tr>
26
<td>
27
<div class="button-tooltip-container">
28
<span title="Click & Copy This ID" onclick="textCopied(this);" class="copybutton">94424</span>
29
<span id="custom-tooltip">copied!</span>
30
</div>
31
</td>
32
</tr>
33
</tbody>
34
</table>
35
</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:
JavaScript
1
14
14
1
function textCopied(el){
2
var inp =document.createElement('input');
3
document.body.appendChild(inp);
4
inp.value = el.textContent;
5
inp.select();
6
document.execCommand('copy',false);
7
inp.remove();
8
var tt = el.parentNode.querySelector(".custom-tooltip");
9
tt.style.display = "inline";
10
setTimeout( function() {
11
tt.style.display = "none";
12
}, 1000);
13
};
14