We are living in a technology era where everything is influenced by technology. Technology has provided many advanced solutions and has overcome many manual efforts. So, in this technology era, manually selecting text and copying it using “ctrl + c” seems old-fashioned and takes a bit of time. So how to automate it?
Well, Thanks to JavaScript! It offers some built-in clipboard properties that allow us to copy/paste the text into the clipboard using a single button click.
In this write-up we will learn how to copy text into a clipboard using HTML and JavaScript:
- How To Copy/Paste Text Into Clipboard Using JavaScript
- Practical Demonstration of Copy/Paste Text Into Clipboard
So let’s begin!
How To Copy/Paste Text Into Clipboard Using JavaScript
The below-given example program will provide you a detailed understanding of how to copy text into clipboard using JavaScript:
CopyPaste.html
In this example, we created an input field and a button, on clicking the button the text will be copied to the clipboard. Next, we created an <p> element and assign it an id “ptext”.
CopyPaste.js
var copyData = document.getElementById("inputText");
var showText = document.getElementById("ptext");
copyData.select();
navigator.clipboard.writeText(copyData.value);
showText.innerHTML = "Text Copied:" + copyData.value;
}
The above snippet serves the below-listed functionalities:
- We created a function named “copyFunction()” which will be invoked when someone clicks on the “Copy” button.
- Within copyFunction(), we utilized the getElementById() method to read HTML elements.
- Next, we utilized the select() method to select the text field.
- Afterward, we utilized the navigator.clipboard.writeText() to copy text into the clipboard.
- Finally, we utilized the innerHTML property to set the name and age on the <p> element.
On successful execution of the program, initially, we will get the below-given output:
If everything goes fine, then clicking on the “Copy” button will show a message “Text copied” alongwith the copied text:
The output authenticates that our program is working perfectly fine.
Practical demonstration
In this section, we will show you the practical demonstration of the above-given program.
The above snippet shows how to copy/paste the text into the clipboard using JavaScript.
Conclusion
JavaScript offers some built-in clipboard properties that allow us to copy/paste the text into the clipboard using a single button click. In JavaScript, the navigator.clipboard is used to get access to the clipboard while writeText() property is used to copy the text into the clipboard. This write-up presents a comprehensive guide on how to copy/paste the text into the clipboard using JavaScript.