A script was made for employees to form an email. Fill in the fields, and below is a letter in the html format (data from the fields are substituted).

The question is how to make a copy button to the clipboard, all that is below the input fields? This is necessary to copy the result (template) after filling in and insert it into the newsletter to customers.

enter image description here

    1 answer 1

    The point is that auto-copying works only for input or textarea elements that are highlighted with the mouse. Therefore, when you click on a button, you must β€œbehind the scenes” first create such an element, paste the necessary text there, select it, copy it, then delete it:

    (function(){ document.getElementById('copy').addEventListener('click', function(){ let area = document.createElement('textarea'); /* Π‘ΠΎΠ·Π΄Π°Π»ΠΈ */ area.value = document.getElementById('mama').innerHTML; /* Вставили тСкст */ document.body.appendChild(area).select(); /* Π”ΠΎΠ±Π°Π²ΠΈΠ»ΠΈ Π½Π° страницу ΠΈ Π²Ρ‹Π΄Π΅Π»ΠΈΠ»ΠΈ */ document.execCommand('copy'); /* Π‘ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Π»ΠΈ */ area.remove(); /* Π£Π΄Π°Π»ΠΈΠ»ΠΈ */ /* Какая-Ρ‚ΠΎ дСкорация, Ρ‡Ρ‚ΠΎΠ±Ρ‹ Π΄Π°Ρ‚ΡŒ ΠΏΠΎΠ½ΡΡ‚ΡŒ, Ρ‡Ρ‚ΠΎ ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Π½ΠΈΠ΅ сработало */ this.innerHTML = 'Π‘ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°<span style="color: red">Π½ΠΎ</span>'; setTimeout(function(){ document.getElementById('copy').innerHTML = 'Π‘ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ'; },2000); }); })(); 
     <div id="mama"> ΠžΠ±Ρ‰ΠΈΠΉ Π±Π»ΠΎΠΊ, ΠΊΡƒΠ΄Π° записан <p> ΠΊΠ°ΠΊΠΎΠΉ-Ρ‚ΠΎ HTML </p> ΠΈ Π½ΡƒΠΆΠ½ΠΎ Π΅Π³ΠΎ ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ <span> mooo </span> </div> <button id="copy">Π‘ΠΊΠΎΠΏΠΈΡ€ΠΎΠ²Π°Ρ‚ΡŒ</button>