Most browsers will only allow copying of text from a visible input box or textarea
Copy function that multiple div boxes can use
<style>
.ClickToCopyBox
{
border: 1px solid #000;
max-width: 600px;
width: 100%;
padding: 6px;
box-sizing: border-box;
overflow-wrap: break-word;
}
.ClickToCopyBox.Copied
{
background: #d4ffd4;
}
</style>
<div class="ClickToCopyBox">
Something that will be copied
</div>
<div class="ClickToCopyBox">
Something else that will be copied
</div>
<div class="ClickToCopyBox" data-copy="Custom text to copy">
This won't be copied, the data-copy="" text will be instead.
</div>
<script>
function CopyElementText(element)
{
let text = element.innerText.trim();
navigator.clipboard.writeText(text)
.then(function()
{
element.classList.add('Copied');
setTimeout(function()
{
element.classList.remove('Copied');
}, 1000);
})
.catch(function(err)
{
console.error('Copy failed:', err);
});
}
document.querySelectorAll('.ClickToCopyBox').forEach(function(el)
{
el.style.cursor = 'pointer';
el.addEventListener('click', function()
{
CopyElementText(el);
});
});
</script>
Providing different text to be copied than the text displayed
Add this to the div tab and it will be used instead:
data-copy="Custom text to copy"
Text area example for wordpress (jQuery)
This example overwrites the textarea value in case user has altered it
<input id="MyElement1" type="textarea" onclick="this.select(); value="The text I want copied" >
<a href="javascript:void(0);" onclick="CopyToClipboard('MyElement1', 'The text I want copied');" >Copy to clipboard</a>
<script>
function CopyToClipboard(InputElementId, RequiredText) {
document.getElementById(InputElementId).value = RequiredText;
var copyText = document.getElementById(InputElementId);
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
document.execCommand("copy");
alert("Copied to your clipboard");
}
</script>
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through resources like this. We hope you find it helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support here. If you need help with a problem please use one of the many online forums.
