Adding "Copy to clipboard" buttons to Google Sites
Google Sites has many good aspects, but it is pretty tight when it comes to customizations.
I have written some pages that ask the reader to copy some code and run it in a command window. The code is typically several lines, and selecting it can be a bit awkward. In fact, one tester missed one character when selecting the text, and confusion ensued.
After a fair amount of bumping into walls, I have finally found something that's not perfect, but it works.
The main challenge is that Google places embed widgets deep in very tightly controlled sandboxes, so forget about accessing the content of the page from your JavaScript code -- that's never happening.
Let's say you want a button that puts the following multi-line text in the clipboard:
Now is the time
Four score and seven years ago
When in the course of human events
Insert an Embed widget and give it the following code:
<p id="txtBuff" style="height: 0px; width: 0px; clip-path: circle(0); font-size: 0px;">
Now is the time<br>
Four score and seven years ago<br>
When in the course of human events<br>
</p>
<button id="butt" type="button" style="background: #3f51b5; color: #FFFFFF; margin-top: 0.5em; border-radius: 6px;" onclick="let node = document.querySelector('#txtBuff'); const selection = window.getSelection(); const range = document.createRange(); range.selectNodeContents(node); selection.removeAllRanges(); selection.addRange(range); document.execCommand('copy'); this.innerHTML = 'Copied'; setTimeout(function(){selection.removeAllRanges();}, 500); setTimeout(function(){document.getElementById('butt').innerHTML = 'Copy to clipboard';}, 2000); console.log('Copy successful');">Copy to clipboard</button>
Unless of course you change its styles. When you click that button, its text will change to "Copied" for two seconds to let the user know that their click was effective, then return to the original "Copy to clipboard".
If you look at the code, you may wonder whether the id attributes need to be changed if you have multiple buttons on the same page. You don't need to worry about that, because each button will be in its own little sandbox and will not clash in any way with the other buttons.
Comments
Post a Comment