In making the page it is very important to include the share feature, at least copy the url with hashtags or other share urls if outside the main url. This time I want to make a button copy like the one created by the bootstrap page, and it will look like this
Prerequire
- Bootstrap; tooltip
- Javascripts; loops, logic etc
- Clipboard.js plugin
Prepare Button
<div class="float-end bd-highlight">
<button type="button" url-site="http://example.org#event" class="btn btn-outline-secondary fw-light link-copy" data-bs-original-title="Copy Url"><i class="bi-share-fill"></i> Share</button>
</div>
In the button there are several attributes and classes that need to be considered, such as the data-bs-original-title="Copy Url"
attribute which will display a tooltip description, the site-url
attribute which will store the url to be saved. and the link-copy
class which will be used as a token class for tooltip activation.
Install tooltip
document.querySelectorAll('.link-copy').forEach(function(a){
var b=new bootstrap.Tooltip(a);
a.addEventListener('mouseleave', function(){
b.hide()}
)
// console.log(a.getAttribute('url-site'));
});
The script will select all items with class link-copy
then will execute the tooltip installation function which is set to activate the tooltip only on hover.
Run Clipboard.js
var d = new ClipboardJS('.link-copy',{
text:function(a){
return a.getAttribute('url-site')
}
});
d.on('success', function(a){
var b = bootstrap.Tooltip.getInstance(a.trigger);
a.trigger.setAttribute('data-bs-original-title','Copied!');
b.show();
a.trigger.setAttribute('data-bs-original-title','Copy Url');
a.clearSelection()
});
The installed clipboard will copy the description from the url-site
, pay attention to the text
description in the script. After a successful copy, the script loads the next few actions, which include a tooltip description that changes after the trigger click is result Copied!
and returns to the default description when another trigger occurs.
Done
Top comments (2)
Very good post.
But what worries me is to see the excessive use of the library when the javascript itself offers a copy of a text (clipboard).
See below for an example.
Hmm.. Simple code.
Thankyou 👍