Reputation: 37
im new to JQuery and a A/B testing tool called Convert. In one of the experiments, I want to add a small piece of text that when a user clicks on it it will copy the text to the clipboard and will show a tooltip saying "Copied!" but for some reason the code is not working, it doesn't shows an eroor, it's like it doesn't even run. I can't find an error and I'm not sure if it may be the tool who is giving me problems but would like somebody with more experience to take a look and tell if I did something wrong to know how to improve.
Here's the HTML:
<a id="copy-promo-btn" href="#">PLUS79</a>
This is the CSS:
.copy-notification {
color: #ffffff;
background-color: rgba(0,0,0,0.8);
padding: 20px;
border-radius: 30px;
position: fixed;
top: 50%;
left: 50%;
width: 150px;
margin-top: -30px;
margin-left: -85px;
display: none;
text-align:center;}
And this is the javascript:
convert.$(document).ready(function() {
$(document).ready(function () {
$("#copy-promo-btn").click(function (event) {
event.preventDefault();
CopyToClipboard("PLUS79", true, "Copied!");
});
});
function CopyToClipboard(value, showNotification, notificationText) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(value).select();
document.execCommand("copy");
$temp.remove();
if (typeof showNotification === 'undefined') {
showNotification = true;
}
if (typeof notificationText === 'undefined') {
notificationText = "Copied!";
}
var notificationTag = $("div.copy-notification");
if (showNotification && notificationTag.length == 0) {
notificationTag = $("<div/>", { "class": "copy-notification", text: notificationText });
$("body").append(notificationTag);
notificationTag.fadeIn("slow", function () {
setTimeout(function () {
notificationTag.fadeOut("slow", function () {
notificationTag.remove();
});
}, 1000);
});
}
}
});
Upvotes: 1
Views: 46
Reputation: 14570
Here is how you can copy to clipboard your text on click event by adding some java-script to your existing code.
.select()
will not work in your case because its ONLY selects the text but its does not copy it which in your case you need to click to copy and paste as well.
Few things added:
Run snippet below to see it working.
$(document).ready(function() {
$("#copy-promo-btn").click(function(event) {
event.preventDefault();
CopyToClipboard("PLUS79");
});
});
function CopyToClipboard(value) {
var copyvalue = document.createElement('input');
copyvalue.value = value
document.body.appendChild(copyvalue);
copyvalue.select();
document.execCommand('copy');
console.log(copyvalue.value)
document.body.removeChild(copyvalue);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="copy-promo-btn" href="#">PLUS79</a>
Upvotes: 1