Posted under » JavaScript on 1 Dec 2023
This refer to my Ajax live search article.
Rather than select and copy you can copy by pressing a button
<script>
function kopy() {
// get the container
const element = document.querySelector('#livesearch');
// Create a fake `textarea` and set the contents to the text
// you want to copy
const storage = document.createElement('textarea');
storage.value = element.innerHTML;
element.appendChild(storage);
// Copy the text in the fake `textarea` and remove the `textarea`
storage.select();
storage.setSelectionRange(0, 99999);
document.execCommand('copy');
element.removeChild(storage);
}
</script>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)">
<p><div id="livesearch"></div>
<div>
<button onclick="kopy()">Copy Me</button>
</div>
</form>
Use JS reduce for text replacements which I personally find confusing.
// you want to copy
const storage = document.createElement('textarea');
kaca = element.innerHTML;
const replacements = [
{ find: "NTU", replace: "NUS" },
{ find: "dog", replace: "cat" },
{ find: "brown", replace: "black" }
];
const rizal = replacements.reduce((currentText, item) => {
return currentText.replaceAll(item.find, item.replace);
}, kaca);
storage.value = rizal;
element.appendChild(storage);
execCommand('copy') is depreciated and is replaced by navigator.clipboard but for this to work it requires https.
function fallbackCopyText(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();
try {
document.execCommand('copy');
console.log('Fallback: Text copied successfully');
} catch (err) {
console.error('Fallback: Unable to copy', err);
}
document.body.removeChild(textArea);
}
// Usage check
if (navigator.clipboard) {
navigator.clipboard.writeText("Hello World");
} else {
fallbackCopyText("Hello World");
}