Taher
Taher

Reputation: 51

JS: Copy an image alt attribute when its clicked

So this is an extinction to the question "copy text string on click"!

here is the code that I want to use to copy the alt image when I click on it

function copy(that){
    var inp =document.createElement('input');
    document.body.appendChild(inp)
    inp.value =that.textContent
    inp.select();
    document.execCommand('copy',false);
    inp.remove();
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>
<span onclick="copy(this)">
  <img 
    style="width:100px;" 
    draggable="false" 
    class="emoji" 
    alt="😀" 
    src="https://s.w.org/images/core/emoji/2.4/svg/1f600.svg">
</span>

the script will copy text when you click it, It needs to be modified so it copy the image alt to the clipboard.

Upvotes: 2

Views: 943

Answers (1)

wscourge
wscourge

Reputation: 11291

Your that argument of copy() is a span element.

  1. Take its first child (img): that.children[0]
  2. Take img.getAttribute("alt")
  3. The rest of your code is good and it works.

function copy(that){
  var inp = document.createElement('input');
  var alt = that.children[0].getAttribute("alt");
  console.log("Copy:", alt);
  document.body.appendChild(inp)
  inp.value = alt
  inp.select();
  document.execCommand('copy',false);
  inp.remove();
}
<link href='https://fonts.googleapis.com/css?family=Oswald' rel='stylesheet' 
type='text/css'>
<span onclick="copy(this)">
  <img 
    style="width:100px;" 
    draggable="false" 
    class="emoji" 
    alt="😀" 
    src="https://s.w.org/images/core/emoji/2.4/svg/1f600.svg">
</span>

Upvotes: 2

Related Questions