Learn How To Copy Text to Clipboard in Javascript

Learn How To Copy Text to Clipboard in Javascript
October 12, 2021

Javascript is a programming language that allows you to execute commands on your browser after it has loaded into the page. In this post, learn how to copy text from one part of the webpage into another using Javascript's clipboard API.

Here we are going to use bootstrap to design HTML components to reduce development time and focus on our main functionality, You can use your own CSS or just include the following bootstrap file in the head tag.

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />

1. Copy Text to Clipboard

HTML Code:

<body class="container">
    <div class="row justify-content-center mt-5">
        <div class="col-md-8 col-sm-12 mb-3">
            <input type="text" class="form-control" id="text" />
        <div class="col-md-8 col-sm-12 mb-3">
            <button class="btn btn-primary" onclick="copyText()">Copy</button>
        <div class="col-md-6 col-sm-12 alert alert-warning alert-dismissible fade show d-none" id="alert" role="alert">
            <span id="alert_text"></span>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
              <span aria-hidden="true">&times;</span>

JavaScript Code:

 function copyText()
      //get input field text
      const inputText = document.getElementById("text");

      //copy text inside text field

      //alerting copied text
      document.getElementById("alert_text").innerHTML = "Copied Text : " + inputText.value;


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Are you looking for Front-end Developer Job?

Get Front-end Interview Kit Now, And Be Prepared to Get Your Dream Job

Get Front-end Interview Kit

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates