How To Copy Text To Clipboard With Sweetalert In Jquery

admin_img Posted By Bajarangi soft , Posted On 15-01-2021

learn how to copy text to clipboard using jquery with sweet alert message

copy-text-to-clipboard-using-jquery

Step 1:Create index.html and implement below html code in it.

<div class="container">
    <div class="col-md-12 bs_card mt-3">
        <h1>Copy text to clipboard using Jquery</h1>
        <div class="col-md-6 mt-3">
            <input class="form-control copy_text" type="text" value="Copy text" readonly>
            <br>
            <button class="btn btn-info" onclick="copyText()">Copy</button>
        </div>
    </div>
</div>

Step 2:Add script for onclick function to copy text
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
<script>
    function copyText(){
        var dummy = $('.copy_text').val();
        $('.copy_text').select();
        document.execCommand('copy');
// sweet alert
        Swal.fire({
            position: 'center',
            icon: 'success',
            title: 'Link Copied',
            text: dummy,
            showConfirmButton: false,
            timer: 1500
        });
    }
</script>

Complete Code For Copy Text To Clipboard Using JQuery.
<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>
</head>
<body>

<div class="container">
    <div class="col-md-12 bs_card mt-3">
        <h1>Copy text to clipboard using Jquery</h1>
        <div class="col-md-6 mt-3">
            <input class="form-control copy_text" type="text" value="Copy text" readonly>
            <br>
            <button class="btn btn-info" onclick="copyText()">Copy</button>
        </div>
    </div>
</div>

<script>
    function copyText(){
        var dummy = $('.copy_text').val();
        $('.copy_text').select();
        document.execCommand('copy');
        Swal.fire({
            position: 'center',
            icon: 'success',
            title: 'Link Copied',
            text: dummy,
            showConfirmButton: false,
            timer: 1500
        });
    }
</script>
</body>
</html>

Related Post