How to use SweetAlert with clipboard.js library? - javascript

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.

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>

Your sweet alert was calling $("#copyBtn").click(); which I am not sure is necessary.
In any case, you have set onclick="copyText();" in this button but never defined a copyText function.
Either define the function or remove the onclick attribute.
Here's working code with an empty copyText function defined.
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
console.log('Copied text: ' + e.text);
});
clipboard.on('error', function(e) {
console.log(e);
});
function copyText() {
}
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");
}
);
/*fit into snippet window*/
.sweet-alert { margin: auto; transform: scale(.75); }
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard#1/dist/clipboard.min.js"></script>
<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>
If you want to fire the alert on the button click then put the swal function inside of the function you defined in onclick:
Your sweet alert was calling $("#copyBtn").click(); which I am not sure is necessary.
In any case, you have set onclick="copyText();" in this button but never defined a copyText function.
Either define the function or remove the onclick attribute.
Here's working code with an empty copyText function defined.
var clipboard = new Clipboard('.btn');
clipboard.on('success', function(e) {
console.log('Copied text: ' + e.text);
});
clipboard.on('error', function(e) {
console.log(e);
});
function copyText()
{
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() {
swal("Copied!", "The text has been copied.", "success");
});
}
/*fit into snippet window*/
.sweet-alert {
margin: auto;
transform: scale(.75);
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard#1/dist/clipboard.min.js"></script>
<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>

Related

Uncaught ReferenceError: buyNft is not defined at HTMLAnchorElement.onclick

Am I missing to add some script or what? I am getting error from title. How can I solve this, if you can help me, I would be grateful. I tried adding different scripts, but I amgetting the same error.
<a onclick="buyNft({{$nft->id}})">{{trans('nft.buy')}}</a>
#push('scripts')
<script>
function buyNft(nftid) {
swal({
title: "Are You Sure?",
text: "Do you want to buy this nft?",
type: 'warning',
showCancelButton: true,
showConfirmButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
}).then((result) => {
if (result) {
axios.post("/buythisnft/" + nftid).then(response => {
window.location.reload();
});
}
});
}
</script>
#endpush
Your buyNft-function needs to be declared BEFORE you echo out any element with "onclick=buyNft()":
#push('scripts')
<script>
function buyNft(nftid) {
// ...
}
</script>
#endpush
<a onclick="buyNft({{$nft->id}})">{{trans('nft.buy')}}</a>
UPDATE: This is an example using a script at the bottom of the page which creates an eventlistener for click-events:
document.addEventListener("click",e => {
if(e.target.closest(".buyNft")){
e.preventDefault();
alert("You want to buy an NFT.")
//... Replace with your own functions ...
}
})
<a class="buyNft" href="#">Buy that NFT</a>
<br /><br />
Some other link on this page

Bootstrap V5 & jQuery: The close event does not return when opened the modal again

I add some special functionality in my modal close event with sweetalert2 but I have faced some issues when I close the modal the first time the close event does not show up again when I opened.
Live Example:
https://codepen.io/themes4all/pen/oNWeYzp
Note:
to know exactly what I'm talking about trying to close the modal and
opened and closed again.
jQuery Code:
(function ($) {
"use strict";
$(window).on("load", function () {
if ($(".modal").length) {
$(".modal").modal("show");
$(".modal").on("shown.bs.modal", function (e) {
e.preventDefault();
$(".spinner")
.removeClass("d-none")
.delay(3000)
.fadeOut(500, function () {
$(this).addClass("d-none");
});
});
$(".modal").on("hide.bs.modal", function (e) {
e.preventDefault();
var swalWithBootstrapButtons = Swal.mixin({
customClass: {
confirmButton: "btn btn-primary",
cancelButton: "btn btn-danger me-3",
},
buttonsStyling: false,
});
swalWithBootstrapButtons
.fire({
title: "Are you sure?",
text: "You won't be able to revert this!",
icon: "warning",
confirmButtonText: "<i class='fas fa-check-circle me-1'></i> Yes, I am!",
cancelButtonText: "<i class='fas fa-times-circle me-1'></i> No, I'm Not",
showCancelButton: true,
reverseButtons: true,
focusConfirm: false,
})
.then((result) => {
if (result.isConfirmed) {
$(this).off("hide.bs.modal").modal("hide");
$(".modal-backdrop").remove();
$("body").removeClass("modal-open").removeAttr("style");
}
});
});
}
});
})(window.jQuery);
Remove the data-bs-dismiss attribute from the close button.
Instead of calling the method on hide, call the sweetalert on the close button click.
And on confirming the sweetalert, just do $(".modal").modal("hide")
This should work.
JSFiddle

Unable to submit form in javascript after sweet alert has been closed

I have created an application that will feature a demo login. The Demo login will have a sweet alert pop up to let the user know that the changes they make will not be saved to the database. The problem is that the form doesn't submit after the user presses ok button that will close the sweet alert. What is the proper syntax to submit the form after the ok button has been pressed?
Below is my html:
<form method="post" id="submitForm" name="demoSubmitForm">
<div class="demo-button pt-3">
<button type="button" name="demoEmail" value="DemoEmail" class="au-btn au-btn--block au-btn--blue
m-b-20" onclick="ShowSweetAlert()">
Demo Application
</button>
</div>
</form>
Below is my script:
function ShowSweetAlert() {
Swal.fire({
icon: 'warning',
title: 'You are logging in as a Demo User!',
text: 'Changes you make to the Application will not be saved once you log out.',
onClose: document.getElementById('submitForm').submit() /*document.demoSubmitForm.submit()*/
});
}
At the moment neither do document.demoSubmitForm.submit() nor document.getElementById('submitForm').submit() work in order to submit the form.
Video of the Problem
Add this Script:
$('#submitForm').on('click', function(e) {
e.preventDefault();
var form = $(this).parents('form');
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
}, function(isConfirm) {
if (isConfirm) form.submit();
});
});

I want to easily chang the color of the icon in Sweealert2, but I get unknown parameter in console

I am following the documentation and it is working wonders. However, using the iconColor property
I get this error in the console: SweetAlert2: Unknown parameter "iconColor". How can I easily change the color of the icon? I could change the color using customClass, but I would prefer to use iconColor as shown in the documentation.
Javascript:
function Delete(e) {
swal.fire({
title: "Do you want to delete?",
text: " You will not be able to undo after deletion",
icon: "warning",
iconColor: "#000",
showCancelButton: true,
focusCancel: true,
confirmButtonColor: '#d33',
confirmButtonText: 'Yes, delete!',
cancelButtonColor: '#3085d6',
cancelButtonText: 'Cancel',
}).then((result) => {
if (result.isConfirmed) {
e.previousElementSibling.click();
}
});
}
<link href="https://cdn.jsdelivr.net/npm/sweetalert2#9.17.2/dist/sweetalert2.min.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#9.17.2/dist/sweetalert2.all.min.js"></script>
<button onclick="Delete(this)" type="button" class="btn btn-sm btn-danger mt-2">Delete</button>
iconColor works for me when trying it in CodePen - It appears this was added in SweetAlert2 10.1.10 (https://github.com/sweetalert2/sweetalert2/pull/2052), and made an updatable param in 10.2.0 (https://github.com/sweetalert2/sweetalert2/issues/2053)
Are you running a version of sweetalert2 later than these? :)

Sweet Alert TextBox Variable

I am very new to PHP and javascript, so my question is fairly simple... I have this JavaScript code (Sweetalert2 text field) And I want to get the information that people type into a separate PHP file using ajax. I am struggling for days now with this problem, would be super grateful if someone showed me how to do it correctly
This is my code
<button type="button" id="new-btn" class="btn btn-primary" onclick="post();">Beitrag Erstellen</button>
<script>
$(document).ready(function () {
$('#new-btn').click(function () {
swal({
title: "Add Note",
input: "textarea",
showCancelButton: true,
confirmButtonColor: "#1FAB45",
confirmButtonText: "Save",
cancelButtonText: "Cancel",
buttonsStyling: true
}).then(function () {
swal(
"Sccess!",
"Your note has been saved!",
"success"
)
})
});
})
</script>
when you run your code, you will get the below error
{
"message": "Uncaught ReferenceError: $ is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 15,
"colno": 9
}
"Uncaught ReferenceError: $ is not defined", means that you have used $ symbol syntax, (that is jquery), but you have not imported it properly and defined it. For this purpose, you can add the below lines at the top of your code. Then it should work as expected.
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
And then, to use swal() in your code, you have to have sweethart script imported which can be done by adding the below one also at the top of your file
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
Finally, your working code file shold be someting like this--->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js">
</script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
</head>
<body>
<button type="button" id="new-btn" class="btn btn-primary" onclick="post();">Beitrag Erstellen</button>
<script>
$(document).ready(function () {
$('#new-btn').click(function () {
swal({
title: "Add Note",
input: "textarea",
showCancelButton: true,
confirmButtonColor: "#1FAB45",
confirmButtonText: "Save",
cancelButtonText: "Cancel",
buttonsStyling: true
}).then(function () {
swal(
"Sccess!",
"Your note has been saved!",
"success"
)
})
});
})
</script>
</body>
</html>

Categories

Resources