1

I'm creating a lorem ipsum generator and have a lot of fun with it. However, I'm trying to create a button where you can copy the generated text. Where am I going wrong with this?

I have a separate javascript file that generates text successfully into just wondering how exactly to copy it

<body>
<center>
    <h1 class="title">Lorem Ipsum Generator</h1>

    <p class="description">A Harry Potter lorem ipsum generator.</p>

    <form action="/" method="POST">
      <input type="number" class="paragraph-number" name="numberOfParagraphs">
      <input type="submit" value="Expecto Patronum!" class="generate-button">
      <input type="reset" value="clear" class="generate-button">

    </form>  </center>

  <center> 
   <div class="border"><div id="generated-text">
      <div class='placeholder-div'></div>
    </div>
    </div>
    
<button onclick="copyPassage()" class="copy-button">Copy text</button>
    
<script src=/generator.js>
function copyPassage() {
  var copyText = document.getElementById("generated-text");
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>
Jess Y.
  • 67
  • 2
  • 8
  • 1
    Check [this answer](https://stackoverflow.com/a/1173319/5734311) –  Jan 15 '19 at 19:10
  • 2
    You shouldn't have a `src` attribute on that script block. That should be two separate script blocks, one empty with the `src` attribute, and the other just with javascript inside of it. – jmcgriz Jan 15 '19 at 19:11

1 Answers1

1

You were close, however a couple things went awry. First, the DOM is evaluated in order, so the onclick handler didn't know about your function as it was declared after the element; this caused an Uncaught ReferenceError: copyPassage is not defined.

Next, the wrong method was used to actually select the text. You used .select() which caused an Uncaught TypeError: copyText.select is not a function.

Instead, for the selection, you should be using selectAllChildren MDN.

See it in action here:

<script>
function copyPassage() {
  var copyText = document.getElementById("generated-text");
  window.getSelection().selectAllChildren(copyText);
  document.execCommand("copy");
  alert("Copied the text: " + copyText.innerText);
}
</script>
<button onclick="copyPassage()" class="copy-button">Copy text</button>
<div class="border">
    <div id="generated-text">
         <div class='placeholder-div'>Harry Potter</div>
    </div>
</div>
    
Travis J
  • 81,153
  • 41
  • 202
  • 273