Copy and Paste Javascript command [duplicate]

5

I need to know how to give ctrl c in a div's contents when clicking on it. In case it will have multiple divs, and it will get the contents of the div clicked.

I found some things on the internet, but wanted something simple. Simply through the onclick grab the contents of the div.

It can be Javascript or Jquery. (Anyone can, whatever works)

Do not need to work on all browsers, just place the javascript command that copies (ctrl + c). Well I think you can help in the community.

Note: I would like to be introduced to a solution that is not using the #

Thankful ...

    
asked by anonymous 27.06.2015 / 15:28

1 answer

3

It's kind of complicated to copy directly to clipboard something via javascript because it does not work well in all browsers, a tactic is to make it easier for the user to copy. Example:

window.onload = function () {
  var divs = document.querySelectorAll('.copiar');
  
  for (var i=0; i<divs.length; i++) {
     divs[i].addEventListener("click", function () {
        prompt("Dê um CTRL + C para copiar e feche.", this.innerHTML);
     });  
  }
}
.copiar {
   border: 1px solid;
   margin: 30px 0;
   cursor: pointer;
}
<div class="copiar">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mauris mi, bibendum sed viverra in, maximus quis mauris. Aenean laoreet mattis orci, vel porta est. Maecenas vel nisi vitae felis auctor imperdiet. Morbi convallis dapibus leo. Nunc maximus ligula id felis porta, vitae tincidunt risus lobortis. Pellentesque mattis mauris at odio sagittis, vitae fermentum arcu ultricies. Donec in cursus enim, id pretium velit. Nunc elementum nunc augue, sed ullamcorper velit fermentum nec. Aliquam erat volutpat. Nulla erat diam, posuere cursus turpis imperdiet, luctus maximus nunc</div>

<a class="copiar">Praesent imperdiet nulla leo, a eleifend velit finibus sit amet. Donec sodales, orci a tincidunt varius, tellus eros dignissim sem, id lobortis neque lectus sed erat. Nam mattis risus et purus pharetra, vel mattis nisl tincidunt. Nunc ornare tempus mauris. Duis molestie volutpat dui eget facilisis. Aenean sagittis elit erat, at ultricies odio varius quis. Proin eu aliquam lacus. Proin et vestibulum leo. Sed porta ullamcorper sagittis. Phasellus commodo non felis nec rhoncus. Praesent placerat, nisl ut condimentum malesuada, ipsum elit pretium orci, eget interdum lacus sem vel libero. Nam dolor elit, malesuada eget rutrum non, efficitur at purus. Interdum et malesuada fames ac ante ipsum primis in faucibus</a>
  

If you want to try something more advanced: link

    
27.06.2015 / 15:38