DEV Community

Cover image for Copy Url Buttom with Bootstrap and Clipboard.js
andysaktia
andysaktia

Posted on • Edited on

Copy Url Buttom with Bootstrap and Clipboard.js

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

Image description

Prerequire

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>


Enter fullscreen mode Exit fullscreen mode

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'));
});


Enter fullscreen mode Exit fullscreen mode

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()
});



Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
saraiva1989 profile image
Daniel Saraiva

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.

Collapse
 
andysaktia profile image
andysaktia

Hmm.. Simple code.
Thankyou 👍