How to Copy Text to the Clipboard with JavaScript | Plantpot

How to Copy Text to the Clipboard with JavaScript

Web Dev
Sponsored links


Full Screen


Sponsored links




<!DOCTYPE html>
<html lang="en">
    <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="">
    <link rel="stylesheet" href="">
    <link rel="stylesheet" type="text/css" href="style.css">
    <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>


@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: "";


function copyText() {
  var text = document.getElementById('text');
  var alertBox = document.getElementById('alert');;
  document.execCommand('copy'); = "block";
  setTimeout(function(){ = "none";