How to use SweetAlert with clipboard.js library?

Viewed 3003

I'm trying to use SweetAlert with the clipboard.js library. I have tried simulating a click on a HTML button when the user confirm on SweetAlert, but it didn't work.

Here is what I've tried to do:

My HTML:

<button class="btn btn-primary" id="copyBtn" data-clipboard-target="#info_block" onclick="copyText();">
    Copy Text!
</button>

<div id="info_block" name="info_block">
    Some example text.
</div>

My JavaScript function:

var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
    console.log(e);
});
clipboard.on('error', function(e) {
    console.log(e);
});

And the structure of my SweetAlert:

swal({
  title: "Copy the text?",
  text: "Are you sure you want to copy it to clipboard?",
  type: "warning",
  showCancelButton: true,
  confirmButtonColor: "#DD6B55",
  confirmButtonText: "Yes, copy it!",
  closeOnConfirm: false
},
function(){
  $("#copyBtn").click(); // simulates click on html button.
  swal("Copied!", "The text has been copied.", "success");
});

It works fine without sweet alert, but it won't work simulating a click on the copy button, and I can't figure out a way to get it working.

2 Answers

With this variant, the newer SweetAlert2.js can be used.

function copyText(){

    var copy = $('.copy_text').val();
    $('.copy_text').select();
    document.execCommand('copy');
    
    Swal.fire({
        icon: 'success',
        title: 'Text copied to clipboard',
        text: copy,
        showConfirmButton: false,
        timer: 3000
    });
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script>

<input type="text" class="copy_text" value="Hello World!">
<button onclick="copyText()">Copy to clipboard</button>

Related