jQuery toggleClass example
Toggle class name on click in jQuery
HTML
<h1 id="mainTitle">Click the button to copy this to clipboard</h1>
<span class="copyButton" data-target="#mainTitle">Copy</span>
<h2 id="secondTitle">Second text you can copy</h2>
<span class="copyButton" data-target="#secondTitle">Copy</span>
<br>
<textarea cols="10" id="copyTextArea" rows="1" spellcheck="false"></textarea>
CSS
.copyButton {
display: inline-block;
color: #FFF;
font-weight: bold;
padding: 3px 8px;
min-width: 65px;
text-align: left;
margin: 3px 0 0;
user-select: none;
line-height: 18px;
font-size: 16px;
border-radius: 7px;
box-shadow: 2px 2px 2px #555;
cursor: pointer;
background: none center right no-repeat #ce5937;
background-image: url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg fill='red' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='20px' height='20px' viewBox='0 0 20 20' version='1.1'%3E%3Cg%3E%3Cpath style=' stroke:none;fill-rule:nonzero;fill:rgb(255,255,255);fill-opacity:1;' d='M 15.78125 2.425781 L 13.738281 2.425781 L 13.738281 2.277344 C 13.738281 1.902344 13.429688 1.59375 13.054688 1.59375 L 11.683594 1.59375 L 11.683594 0.683594 C 11.683594 0.304688 11.375 0 11 0 L 9 0 C 8.625 0 8.316406 0.304688 8.316406 0.683594 L 8.316406 1.59375 L 6.945312 1.59375 C 6.570312 1.59375 6.261719 1.902344 6.261719 2.277344 L 6.261719 2.425781 L 4.21875 2.425781 C 3.710938 2.425781 3.296875 2.839844 3.296875 3.351562 L 3.296875 19.074219 C 3.296875 19.585938 3.710938 20 4.21875 20 L 15.78125 20 C 16.289062 20 16.703125 19.585938 16.703125 19.074219 L 16.703125 3.351562 C 16.703125 2.839844 16.289062 2.425781 15.78125 2.425781 Z M 6.953125 5.398438 L 13.050781 5.398438 C 13.414062 5.398438 13.710938 5.101562 13.710938 4.738281 L 13.710938 4.007812 L 15.320312 4.007812 L 15.324219 18.535156 L 4.679688 18.539062 L 4.679688 4.007812 L 6.292969 4.007812 L 6.292969 4.738281 C 6.289062 5.101562 6.585938 5.398438 6.953125 5.398438 Z M 6.953125 5.398438 '/%3E%3C/g%3E%3C/svg%3E");
}
.copyButton:hover {
background-color: #0769AD
}
textarea#copyTextArea {
opacity: 0.01;
width: 2px;
height: 2px;
}
JavaScript
var copyBuffer;
$(document).ready(function() {
$(".copyButton").click(function() {
copyBuffer = $(this).attr("data-target");
$("#copyTextArea").val($(copyBuffer).html());
$("#copyTextArea").focus();
$("#copyTextArea").select();
try {
var successful = document.execCommand('copy');
var msg = successful ? 'successful' : 'unsuccessful';
$(".copyButton").text("Copied");
} catch (err) {
$(".copyButton").text("Error");
}
setTimeout(function() {
$(".copyButton").text("Copy");
}, 2000);
});
});