How to copy text to clipboard using javascript

HTML
<div class="container">
    <div class="input-box">
        <input type="text" class="text">
        <button class="copy-button" type="button">
            <img src="copy.png">
            <div class="copied-message">
                <span class="span">Copied</span>
            </div>
        </button>
    </div>
</div>
CSS
*{
    padding:0;
    margin:0;
}
.container{
    width:100%;
    height:100vh;
    background:linear-gradient(45deg,#43415c,#000);
    position:relative;
}
.input-box{
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    width:300px;
    background-color:#fff;
    border-radius:100px;
    display:flex;
    align-items:center;
    padding:10px 20px;
}
.input-box input{
    width:100%;
    font-size:25px;
    border:none;
    outline:none;
    padding:5px 0px;
    border-right:1px solid #000;
}
.copy-button{
    border:none;
    background-color:transparent;
}
.copy-button img{
    width:40px;
    height:40px;
    margin-left:20px;
    cursor:pointer;
}
.copied-message{
    position:absolute;
    pointer-events:none;
    top:0px;
    opacity:0;
    transition:0.2s;
}
.span{
    position:absolute;
    background-color:#fff;
    color:#000;
    font-size:20px;
    padding:8px 12px;
    border-radius:6px;
}
.span::before{
    position:absolute;
    content:'';
    top:30px;
    width:12px;
    height:12px;
    background-color:#fff;
    transform:rotate(45deg);
    left:40px;
}
.active{
    opacity:1;
    top:-70px;
}
JS
let copy_button = document.querySelector('.copy-button');
let copied_message = document.querySelector('.copied-message');
let text = document.querySelector('.text');

copy_button.onclick = function(){
    navigator.clipboard.writeText(text.value);
    copied_message.classList.add('active');
    setTimeout(() => {
        copied_message.classList.remove('active');
    },2000);
}

/* All credits to: https://www.youtube.com/watch?v=NQZv5aq3r5o */

Autor: Compositu

Publicado: 13/03/2023

Compartir Elemento Web

Donar a Compositu
Otras formas de ayudar
  • Compártelo en tus redes sociales.
  • Recomienda los elementos.
  • Regístrate Aquí
  • Deja tu comentario agradeciendo el aporte.

Descarga el código completo del Elemento Web y archivos necesarios (imágenes, librerias, plugins, frameword, etc)

Deja tu comentario