Copy Text to the Clipboard using JavaScript

How to Copy Text to the Clipboard using JavaScript?

Here I will show you how to Copy text to the Clipboard using JavaScript.

The JavaScript writeText() method of the navigator.clipboard API is used to Copy text to the clipboard.

The writeText method takes a text as an argument that will be copied. Here is the syntax –

//the text "Hi" will be copied
navigator.clipboard.writeText("Hi")

Since this writeText method is asynchronous, it returns a promise.

navigator.clipboard.writeText(value).then(() => {
    console.log('Text copied to clipboard');
}).catch((err) => {
    console.log('Failed to copy', err);
});

Copy text to Clipboard with JavaScript

Here is an example of a copy to the clipboard where we can copy the text of an input field by clicking on a button.

<h1>Copy Text to the Clipboard</h1>
<div class="container">
    <div class="wrapper">
        <span class="msg">Copied</span>
        <input type="text" id="field" value="Hi, How are you?">
        <button id="btn">Copy</button>
    </div>
</div>
<script>
    const copyBtn = document.getElementById('btn');
    const inputField = document.getElementById('field');
    const flashMsg = document.querySelector('.msg');
    copyBtn.onclick = function(){
        const value = inputField.value;
        navigator.clipboard.writeText(value)
        .then(() => {
            if(!flashMsg.classList.contains('show-msg')){
                flashMsg.classList.add('show-msg');
                setTimeout(() => {
                flashMsg.classList.remove('show-msg');
                },2000)
            }
        }); 
    }
</script>
@import url("https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;700&display=swap");

*,
*::before,
*::after {
  box-sizing: border-box;
  line-height: 1.5em;
}

html {
  font-size: 16px;
  scroll-behavior: smooth;
  -webkit-text-size-adjust: 100%;
}

body {
  margin: 0;
  background-color: #f7f7f7;
  color: #222222;
}

body,
input, button {
  font-family: "Open Sans", sans-serif;
  font-size: 1rem;
}

h1 {
  text-align: center;
  padding: 20px;
}

.wrapper {
  max-width: 400px;
  margin: 0 auto;
  display: flex;
  gap: 5px;
  position: relative;
}

.msg {
  position: absolute;
  top: -30px;
  left: 0;
  background-color: #222222;
  border-radius: 30px;
  padding: 1px 10px;
  color: #fcfcfc;
  font-size: 14px;
  opacity: 0;
  visibility: hidden;
  translate: 0 24px;
  transition: 0.2s;
}

.show-msg {
  visibility: visible;
  translate: 0 0;
  opacity: 1;
}

#field, #btn {
  padding: 10px;
  border: 1px solid #bbb;
  border-radius: 3px;
  outline: none;
}
#field:hover, #field:focus, #btn:hover, #btn:focus {
  border-color: #222222;
}

#field {
  flex: 1;
}

#btn {
  cursor: pointer;
}