Copy Text to Clipboard with a Simple Line of JavaScript

Faraz

By Faraz -

Learn how to easily copy text to clipboard with just one line of JavaScript code. Follow our step-by-step guide and improve your web development skills.


copy text to clipboard with a simple line of javascript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Preview
  6. Conclusion

Copying to clipboard refers to the action of copying data, such as text or images, to a temporary storage area on your computer's memory known as the clipboard. This data can then be pasted elsewhere, such as in a document or an email, by using the paste command. Copying to clipboard is a useful feature in computing and is used frequently to copy and paste information from one source to another.

A blog article with a helpful tutorial that explains how to copy text from a website into the clipboard with JavaScript. With this method, you don't have to save the text on your computer first - it'll automatically be copied directly into the clipboard when you click on a button.

Let's start making an amazing copy to clipboard button using HTML, CSS, and JavaScript step by step.

Watch Full Tutorial on my YouTube Channel: Watch Here

Join My Telegram Channel to Download the Project: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our copy to clipboard button and textbox.

Let's go through the code step by step. The first line declares the document type as HTML. The second line begins the HTML document and sets the language to English.

The "head" section of the document contains metadata and links to external resources that the web page will use. The "title" element sets the title of the web page to "Copy Text to Clipboard." The "meta" element sets the character encoding to UTF-8 and the viewport to the width of the device. Finally, the "link" element links to an external stylesheet called "styles.css" that contains the styling rules for the web page.

The "body" section of the document contains the visible content of the web page. It begins with a "div" element with a class of "container," which is a common pattern used to group related content together. The "h1" element sets the heading of the web page to "Copy to clipboard."

Below the heading, there is an "input" element with a class of "copy-text" that has a default value of "codewithfaraz.com". This is the text that the user can copy to the clipboard. There is also a "button" element with a class of "copy-button" that the user can click to copy the text.

Finally, there is a "textarea" element with a class of "testTextArea" that serves as a placeholder for the text that the user can paste into. It has a default of four rows for the user to input the text.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

This is the basic structure of our copy to clipboard using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the copy to clipboard page is in place, the next step is to add styling to the copy to clipboard page using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our copy to clipboard page.

Let's go through the code to understand what each part does.

The first few lines use the universal selector (*) to apply the box-sizing property to all elements on the page. This property tells the browser how to calculate the size of an element. In this case, the "border-box" value means that the element's width and height include the padding and border.

The "body" selector defines the styles for the body of the page. It sets the background color to a light pinkish color (#ebddd9) and sets some other properties like display, height, width, padding, and margin. These properties are used to center the content of the page and ensure that it takes up the full width of the viewport. The "max-width" property limits the width of the content to 1200 pixels on larger screens, and the "text-align" property aligns the text to the left.

The "container" selector defines the styles for a container element that holds the page content. It uses flexbox to center the content vertically and horizontally, and "align-items" centers the content vertically.

The "h1" selector defines the styles for the main heading of the page. It sets the font size to be 3% of the viewport width, and it converts the text to uppercase.

The "@media" rule applies the styles within the braces to the page when the screen width is less than or equal to 768 pixels. In this case, it reduces the font size of the "h1" heading and aligns the text to the center.

The "input", "button", and "textarea" selectors define the styles for form elements like input fields and buttons. They set properties like width, background color, border, and padding to create a consistent look across all form elements.

Finally, the "success" class defines a style that is applied to an element when an action is successful. In this case, it changes the background color of the element to a teal color (#0d8b79).

Overall, this CSS code creates a clean, responsive layout for a web page, and it provides consistent styles for form elements.

This will give our copy to clipboard button and textbox an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  background: #ebddd9;
  display: flex;
  flex-direction: column;
  justify-content: center;
  height: 100vh;
  width: 100%;
  padding: 10vw;
  text-align: left;
  max-width: 1200px;
  margin: auto;
}

.container{
  display: flex;
  flex-direction: column;
  align-items: center;
}

h1 {
  font-size: 3vw;
  text-transform: uppercase;
}
@media (max-width: 768px) {
  h1 {
    font-size: 2rem;
    text-align: center;
  }
}

input {
  margin: 1em;
  display: inline-flex;
  width: 200px;
  background: none;
  padding: 1rem;
  border: 1px solid #222;
  outline: none;
  -moz-appearance: none;
  -webkit-appearance: none;
}

button {
  display: inline-flex;
  background: #222;
  width: 100px;
  justify-content: center;
  -moz-appearance: none;
  -webkit-appearance: none;
  color: #f7f7f7;
  padding: 1rem;
  border: 0;
  border-radius: 10px;
  font-weight: 500;
  transition: 2s;
  cursor: pointer;
}

textarea {
  margin: 1em;
  display: inline-flex;
  width: 200px;
  background: none;
  padding: 1rem;
  border: 1px solid #222;
  outline: none;
  -moz-appearance: none;
  -webkit-appearance: none;
}

.success {
  background: #0d8b79;
  transition: 0.3s;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function for copying text into the clipboard using JavaScript.

Let's go through the code to understand what each part does.

The first two lines use the "querySelector" method to get references to two elements on the page: a button with a class of "copy-button" and an input field with a class of "copy-text". These elements will be used later in the event listener.

The "addEventListener" method is called on the "copyButton" element, which listens for a "click" event. When the button is clicked, the function inside the parentheses is executed.

The function that's executed when the button is clicked does the following:

  1. Calls the "select" method on the "copyText" element to select the contents of the input field.
  2. Calls the "setSelectionRange" method on the "copyText" element to set the selection range of the input field to the first and last characters of the text.
  3. Calls the "execCommand" method on the "document" object to execute the "copy" command, which copies the selected text to the clipboard.
  4. Toggles the "success" class on the "copyButton" element to change its background color to green.
  5. Changes the text inside the button to say "Copied!" instead of "Copy".
  6. Sets a timeout function that waits for two seconds and then toggles the "success" class and changes the text back to "Copy".

Overall, this JavaScript code creates a function that copies the contents of an input field to the clipboard when a button is clicked. It provides visual feedback to the user by changing the button background color and text to indicate a successful copy operation.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file. Remember, you’ve to create a file with .js extension.

const copyButton = document.querySelector(".copy-button");
const copyText = document.querySelector(".copy-text");

copyButton.addEventListener("click", () => {
  copyText.select();
  copyText.setSelectionRange(0, 99999);
  document.execCommand("copy");
  copyButton.classList.toggle("success");
  copyButton.innerHTML = "Copied!";

  setTimeout(function () {
    copyButton.classList.toggle("success");
    copyButton.innerHTML = "Copy";
  }, 2000);
});

Final Output:

copy text to clipboard with a simple line of javascript.gif

Conclusion:

In conclusion, copying text to clipboard with JavaScript is a simple and useful feature to implement in web development. By following the steps outlined in this tutorial, you can easily create a button that allows users to copy text with just one click. This can greatly improve the usability of your website, especially for forms and other text-based input elements. We hope that this tutorial has been helpful and that you can apply this knowledge to your own web development projects.

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post