Copy Text From Inputs Or Any HTML Elements – Kopasin.js

Category: Javascript , Text | August 19, 2024
Authormasgalih320
Last UpdateAugust 19, 2024
LicenseMIT
Tags
Views28 views
Copy Text From Inputs Or Any HTML Elements – Kopasin.js

Kopasin is a lightweight yet robust JavaScript copy-and-paste library that lets users copy text from input fields and specified elements.

This library is easy to implement and allows for various use cases. It can be used in online forms, dashboards, and any web application where text needs to be copied frequently.

At its core, Kopasin-JS interacts with the browser’s Clipboard API.

When a copy event is triggered, it selects the content of the source element, writes it to the clipboard using navigator.clipboard.writeText(), and executes the success callback.

The paste functionality follows a similar principle, reading from the clipboard with navigator.clipboard.readText() and populating the target element.

How to use it:

1. Download kopasin-js.global.js and add it to your webpage:

<script src="dist/kopasin-js.global.js"></script>

2. Or install the Kopasin package using NPM:

# NPM
$ npm install kopasin-js
import KopasinJS from "kopasin-js"

3. Define the HTML element containing the text you want users to copy (source) and the element that will initiate the copy action (trigger). This can be a button, an image, or any other interactive element.

<!-- Input Field -->
<input type="text" id="copy-this" value="CSScript.Com" readonly>
<button type="button" id="copy-button">Copy Text</button>
<!-- HTML Element -->
<div id="copy-this">CSSScript.Com</div>
<button type="button" id="copy-button">Copy Text</button>

4. Create a new instance of Kopasin.js, passing an object containing configuration options. Within this object, you’ll specify the source element, trigger element, and the event that will trigger the copy action (default is “click”).

new Kopasin({
  copy: {
    on: 'click',
    trigger: document.getElementById('copy-button'),
    source: document.getElementById('copy-this'),
  },
});

5. You can define success and error callback functions to execute after a copy operation is successful or encounters an error. These functions allow you to customize the user experience with messages or actions.

new Kopasin({
  copy: {
    on: 'click',
    trigger: document.getElementById('copy-button'),
    source: document.getElementById('copy-this'),
    success: function () {
      console.log('Copied!')
    },
    error: function () {
      console.log('Failed to copy')
    }
  },
});

6. The library also provides a Paste function similar to the copy.

new Kopasin({
  paste: {
    on: 'click',
    trigger: document.getElementById('paste-button'),
    source: document.getElementById('paste-this'),
    success: function () {
      console.log('Pasted!')
    },
    error: function () {
      console.log('Failed to paste')
    }
  },
});

You Might Be Interested In:


Leave a Reply