Reputation: 21
I swear I searched and did not find this question. Sorry if I have done a mistake!
ATTENTION: I want to use JavaScript ONLY! I don't want to include jQuery library! There are many examples out there using jQuery, but they don't help me.
Problem: I am creating a website and I am using Bootstrap 5 + Popper. I have some E-Mail addresses written in the content. Each E-Mail address is embedded within an HTML anchor. For each E-Mail address I show a "Copy address" tooltip on hovering it. When the anchor text (the E-Mail address) is clicked I want to copy the Email-Adress into the clipboard so the user can paste it into whatever E-Mail client they use. After clicking the E-Mail address the tooltip title should be changed to "Copied" as confirmation for the user.
HTML code:
<a href="#" data-bs-toggle="tooltip" title="" data-bs-original-title="Copy address">[email protected]</a>
...
<!-- This input text field is used to copy the text (E-Mail addresses) via JavaScript -->
<input type="text" id="copy_input" readonly style="position: absolute; left: -9999px;">
The JavaScript initialization for the Popper tooltip (just as it is on the Bootstrap page for Tooltip):
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl);
});
And here goes my JavaScript code that can copy the E-Mail address into the clipboard BUT IS NOT ABLE to change the tooltip title:
tooltipTriggerList.forEach(function(alink) {
alink.addEventListener('click', function(e) {
e.preventDefault();
const copy_input = document.querySelector('#copy_input');
copy_input.value = alink.textContent.trim();
copy_input.select();
document.execCommand('copy');
copy_input.value = '';
alink.setAttribute('data-bs-original-title', 'Copied');
alink.setAttribute('title', 'Copied'); // just to be sure...
alink.show(); // I thought show() would re-display the changed title, but no!
});
});
Unfortunately the tooltip title is not changed by the listener function above.
Thanks for your help!
Upvotes: 2
Views: 1275
Reputation: 2064
The error relies on that the show method should be called on the tooltip object insted of the link element
tooltipTriggerList.forEach(function(alink) {
alink.addEventListener('click', function(e) {
e.preventDefault();
// do the copy logic ....
// change title for tooltip
alink.setAttribute('data-bs-original-title', 'Copied');
// show the tooltip with the new title
bootstrap.Tooltip.getInstance(alink).show()
});
});
Upvotes: 1