How to Copy Text to the Clipboard with JavaScript

01/26/2021

Contents

Demo

Full Screen

Code

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Copy Text to Clipboard with JavaScript</title>
    <link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
    <link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>
  <body>
    <div id="container">
      <form class="form">
        <input id="text" class="form-input" type="text" placeholder="Type Text...">
        <img class="copy" src="ic_copy.svg" onclick="copyText()">
        <div id="alert" class="alert">Copied Text to the Clipboard.</div>
      </form>
    </div>
  </body>
</html>

CSS

@charset "utf-8";
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
html {
  font-size: 16px;
}
body {
  background-color: #0aa387;
  font-family: futura-pt, sans-serif;
  -webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
  padding: 30px 15px;
}
.form {
  position: relative;
  width: 100%;
  max-width: 300px;
}
.form-input {
  width: 100%;
  height: 50px;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  color: #152024;
  font-size: 1.25rem;
  outline: none;
}
.copy {
  position: absolute;
  top: 15px;
  right: 10px;
  width: 20px;
  cursor: pointer;
}
.copy:hover {
  opacity: .8;
}
.alert {
  display: none;
  position: absolute;
  top: -65px;
  left: 0;
  width: 100%;
  padding: 10px;
  background-color: #fff;
  font-size: 1.25rem;
  color: #152024;
  text-align: center;
}
.alert:before {
  position: absolute;
  top: 100%;
  left: 50%;
  margin-left: -15px;
  border: 15px solid transparent;
  border-top: 15px solid #fff;
  content: "";
}

JavaScript

function copyText() {
  var text = document.getElementById('text');
  var alertBox = document.getElementById('alert');
  text.select();
  text.setSelectionRange(0,9999);
  document.execCommand('copy');
  alertBox.style.display = "block";
  setTimeout(function(){
    alertBox.style.display = "none";
  },1000);
}