Reputation: 1213
My goal is to copy an image to the clipboard. Given it is not allowed to copy image due to security reason, the use case I want to tackle is:
ctrl + c
to copy the imageThe problem is that if I do this for an input, I can easily select the text inside that, but I am not able to do it for an image. Below is the abstracted version of what I am trying to do, mainly just select the image for now.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#myImage").focus();
$("#myImage").select();
});
</script>
</head>
<body>
<img id="myImage" width="220" height="277" src="https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg" alt="The Scream">
</body>
</html>
Below is the same example but for an input and it works.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#myInput").focus();
$("#myInput").select();
});
</script>
</head>
<body>
<input id="myInput" value="hello"/>
</body>
</html>
If somebody can give me the correct of way doing this it would be appreciated. Thanks.
Upvotes: 1
Views: 287
Reputation: 91
$(document).ready(function(){
$("#myImage").bind('load', function(){
$("#myImage").focus();
$("#myImage").select();
alert("ok");
});
});
And you should also check this: jQuery callback on image load (even when the image is cached)
Upvotes: 0
Reputation: 1213
I used clipboard.js to solve my problem and found a way to copy an image to clipboard with just a button. The following was my solution.
note it will not work until you download the cliboardjs.
<!DOCTYPE html>
<html>
<head>
<script src="clipboard.min.js"></script>
<title></title>
</head>
<body>
<div id="myDiv">
<img width="220" height="277" src="https://pixabay.com/static/uploads/photo/2015/10/01/21/39/background-image-967820_960_720.jpg" alt="The Scream">
</div>
<button class="btn" data-clipboard-target="#myDiv">
Copy to clipboard
</button>
<script type="text/javascript">
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
e.clearSelection();
});
</script>
</body>
</html>
Upvotes: 1