Copy content from a div by clicking a button

Asked

Viewed 7,725 times

1

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

I’m trying something like this:

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

The HTML is like this

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

Syntax is not Ok, someone has done something similar, maybe with Jquery?

  • You can post the relevant HTML?

  • I edited the question.

  • Felipe: you want to copy teste1.1 and change the COPIAR to be teste1.1? have other fields where you want to do the same? with ids also?

2 answers

3


Good evening, maybe I’m talking more of the same but I think it is worth mentioning that, taking into account the fact that Felipe does not present in his code the use of Jquery, and Anmaia recommend, I would like to propose only two more details in Anmaia’s proposal, being them:

1 - Include CDN on your website:

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

2 - The inclusion of Jquery Ready in the sample code:

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

http://api.jquery.com/ready/

But I think it’s just that.

1

To do the same with jQuery is the following:

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

This code snippet will copy the value of btCopia for link.

Suggestion

Modify your html and javascript to capture this in an easier way. You are using onload in your javascript, maybe 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 button btCopiar the content of paraCopiar goes to link.

  • Only child elements of the element that has id btCopia?

  • @Patrick see if the suggestion in my reply helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.