This worked across all browsers (as of 2016). I have uploaded on GitHub as well: https://github.com/owaisafaq/copier-js
//Cross-browser function to select content
function SelectText(element) {
var doc = document;
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(".copyable").click(function(e) {
//Make the container Div contenteditable
$(this).attr("contenteditable", true);
//Select the image
SelectText($(this).get(0));
//Execute copy Command
//Note: This will ONLY work directly inside a click listenner
document.execCommand('copy');
//Unselect the content
window.getSelection().removeAllRanges();
//Make the container Div uneditable again
$(this).removeAttr("contenteditable");
//Success!!
alert("image copied!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>
<div class="copyable">
<img src="https://via.placeholder.com/80" alt="Copy Image to Clipboard via Javascript." />
</div>