Copy content from a div when you click a button

1

I have a URL shorter, where there is listing with all generated links. What I need is to create a button next to it, where when the person clicks on it, automatically copy the div that contains the shortened link.

I'm trying something like this:

window.onload = function() {
document.getElementById("link").innerHTML = document.getElementById("btCopia").innerHTML;
}

HTML is like this

<div id="link">teste1.1</div>
<div id="btCopia">COPIAR</div>

The syntax is not Ok, has anyone done anything like this, maybe with Jquery?

    
asked by anonymous 19.07.2014 / 04:19

2 answers

3

Good evening, maybe I'm talking about more of the same but I think it's worth mentioning that, given that Felipe does not use Jquery's code in his code, and that Anmaia recommends, I'd like to propose two more details in the proposal of Anmaia, they are:

1 - Include the CDN on your page:

<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

2-AddingJqueryReadyinthesamplecode:

<script>$(function(){$("#btCopiar").on("click", function(){
          $("#link").text($("#paraCopiar").text());
      });
 });
 </script>

link

I do not think that's all.

    
19.07.2014 / 06:28
1

To do the same with jQuery is as follows:

$("#link").text($("#btCopia").text())

This code snippet will copy the value from btCopia to link .

Suggestion

Modify your html and javascript to capture this in an easier way. You are using onload in your javascript, perhaps the following code will improve your implementation:

<div id="link">[Valor do link]</div>
<div id="paraCopiar">[Esse valor deve ser copiado para #link]</div>

<button id="btCopiar">Copiar</button>

<script>

$("#btCopiar").on("click", function(){
   $("#link").text($("#paraCopiar").text());
});

</script>

That way every time you click the btCopiar button the contents of paraCopiar goes to link .

    
19.07.2014 / 06:13