Do you need to copy text URL ?
At some project, you need to copy text at clipboard, like as copy URL git or URL at this page.
That will simpler more when use plugin clipboard js.
I have use it and practice like a exercise.
If you have the way simple and effective, please share comfortable it.
How to use it?
You can get it on npm: npm install clipboard --save
Else you can down package at here: https://github.com/zenorocha/clipboard.js/archive/master.zip
I have get link cdn like this to use: https://cdn.jsdelivr.net/clipboard.js/1.5.10/clipboard.min.js
Browser Support?
- Chrome 42+
- Edge 12+
- Firefox 41+
- IE 9+
- Opera 29+
- Safari 10+
Example
Html
<div class="c-text">
<button class="c-btn">Copy</button>
<input type="hidden" id="url" value="!">
</div>
Scss
.c-text{
width: 100%;
height: 100%;
text-align: center;
margin-top:10px;
.c-btn{
background-color: #f4f141;
border: transparent;
border-bottom: 2px solid #f4ce42;
border-radius: 2px;
padding: 10px;
min-width: 100px;
color: #f4a341;
}
}
JS
- Element input have id
url
is place get URL page local, to do this, we will assign value for id:$("#url").val(location.href);
- Next, create new variable for Clipboard with value return will be enter at element input.
- To announce for user that copy text success, clipboard support 2 event "success" hoặc "error"
Let's try to do it!
$("#url").val(location.href);
var Clipboard = new Clipboard('.c-btn', {
text: function() {
return document.querySelector('input[type=hidden]').value;
}
});
Clipboard.on('success', function(e) {
e.clearSelection();
});