12% off of LTD using this coupon: TWELVEPERCENTOFF. Promo ends on 2 Dec midnight UTC.
Published on Sep 4, 2021

How to copy hidden input’s text to clipboard

Sridhar Katakam

This tutorial provides the steps to implement W3schools’ How TO – Copy Text to Clipboard article in Oxygen with a couple of changes.

We shall

  1. set the input to be hidden.
  2. ensure that iOS keyboard does not open after the Copy button is tapped.

Step 1

In the Oxygen editor add a Code Block inside a Section.

PHP & HTML:

<!-- The text field -->
<input value="Hello World!" id="copy-to-clipboard-input" type="hidden">

<!-- The button used to copy the text -->
<div class="tooltip">
	<button id="copy-to-clipboard-button">
		<span class="tooltiptext" id="myTooltip">Copy to clipboard</span>
		Copy text
	</button>
</div>

Replace “Hello World!” with the text that should get copied to the clipboard.

JavaScript:

jQuery(document).ready(function($) {
	$('#copy-to-clipboard-button').on('click', function(e) {
		e.preventDefault();
		
		/* Get the text field */
		var copyText = document.getElementById("copy-to-clipboard-input");
		
		/* Prevent iOS keyboard from opening */
		copyText.readOnly = true;

		/* Change the input's type to text so its text becomes selectable */
		copyText.type = 'text';

		/* Select the text field */
		copyText.select();
		copyText.setSelectionRange(0, 99999); /* For mobile devices */

		/* Copy the text inside the text field */
		navigator.clipboard.writeText(copyText.value);

		/* Replace the tooltip's text */
		var tooltip = document.getElementById("myTooltip");
		tooltip.innerHTML = "Copied: " + copyText.value;

		/* Change the input's type back to hidden */
		copyText.type = 'hidden';
	});
	
	$('#copy-to-clipboard-button').on('mouseout', function(e) {
		var tooltip = document.getElementById("myTooltip");
		tooltip.innerHTML = "Copy to clipboard";
	});
});

Step 2

Add this in a Stylesheet at Manage → Stylesheets:

.tooltip {
	position: relative;
	display: inline-block;
}

.tooltip .tooltiptext {
	visibility: hidden;
	width: 140px;
	background-color: #555;
	color: #fff;
	text-align: center;
	border-radius: 6px;
	padding: 7px 5px;
	position: absolute;
	z-index: 1;
	bottom: 150%;
	left: 50%;
	margin-left: -75px;
	opacity: 0;
	transition: opacity 0.3s;
	font-size: 14px;
}

.tooltip .tooltiptext::after {
	content: "";
	position: absolute;
	top: 100%;
	left: 50%;
	margin-left: -5px;
	border-width: 5px;
	border-style: solid;
	border-color: #555 transparent transparent transparent;
}

.tooltip:hover .tooltiptext {
	visibility: visible;
	opacity: 1;
}

References

https://stackoverflow.com/a/57192718/778809

https://stackoverflow.com/a/55422026/778809

tagschevron-leftchevron-rightchainangle-rightangle-upangle-downfolder-omagnifiercrossmenuchevron-downarrow-right