I have built a "snippets" HTML document in which I have dozens various snippets with their codes in a "readonly" textarea. So the snippets may be easily copied inthe clipboard and pasted into a webpage content. I don't know, how to pack the whole "onClick" content into one function. This would save a lot of code in the whole "snippets" document, instead of using this onClick="" in each included snippet. This is my code:
<h2><em>Snippet:</em> Intro page - bold text</h2>
<form>
<input title="One click transfers the code to the clipboard" type="button" value="Hilight & copy the code" onClick="this.form.code.select(),this.value = 'Hilighted code copied', document.execCommand('copy')">
<textarea name="code" readonly="readonly">
<!-- SNIPPET START -->
*snippet code here*
<!-- SNIPPET END -->
</textarea>
</form>
Your code should use ; instead of , but if you have more than one snippet, you should delegate
document.getElementById("container").addEventListener("click", function(e) {
let tgt = e.target.closest("input");
if (tgt && tgt.matches(".copy")) {
const textarea = tgt.nextElementSibling;
textarea.select();
tgt.value = 'Hilighted code copied';
document.execCommand('copy')
}
else tgt = e.target.closest("textarea");
if (tgt.matches("[name=code]")) tgt.select()
})
<div id="container">
<h2><em>Snippet:</em> Intro page - bold text</h2>
<input class="copy" title="One click transfers the code to the clipboard" type="button" value="Hilight & copy the code" />
<textarea name="code" readonly="readonly">
<!-- SNIPPET START -->
*snippet code 1 here*
<!-- SNIPPET END -->
</textarea>
<h2><em>Snippet:</em> Intro page - bold text</h2>
<input class="copy" title="One click transfers the code to the clipboard" type="button" value="Hilight & copy the code" />
<textarea name="code" readonly="readonly">
<!-- SNIPPET START -->
*snippet code 2 here*
<!-- SNIPPET END -->
</textarea>
</div>
Solved. The document must be *.PHP. The variable shall be declared, e.g.:
<?php
$BTN = '<input class="copyBtn" title="Click to hilight & copy" type="button" value="Hilight & copy the code" />';
?>
The usage then is:
<?php echo $BTN;?>