1

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:

  1. the user presses copy button
  2. through jquery select the image (focus and select)
  3. prompt the user to press ctrl + c to copy the image

The 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.

Zaid Qureshi
  • 1,199
  • 1
  • 8
  • 15
  • 1
    Image elements don’t have a `select` method. Try http://stackoverflow.com/questions/4183401/can-you-set-and-or-change-the-user-s-text-selection-in-javascript – CBroe Apr 01 '16 at 18:46

2 Answers2

1

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>
Zaid Qureshi
  • 1,199
  • 1
  • 8
  • 15
0
$(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)

Community
  • 1
  • 1
Mellon
  • 85
  • 1
  • 6