allowOutsideClick not working in SweetAlert2 - javascript

function show_alert(args) {
Swal.fire({
icon: args.icon,
title: args.title,
text: args.message,
html: args.html,
allowEscapeKey: args.allowEscapeKey ? args.allowEscapeKey : true,
allowOutsideClick: args.allowOutsideClick ? args.allowOutsideClick : true,
confirmButtonText: args.confirmButtonText ? args.confirmButtonText : 'Tamam',
confirmButtonColor: args.confirmButtonColor ? args.confirmButtonColor : '#3085d6',
cancelButtonText: args.cancelButtonText ? args.cancelButtonText : 'İptal',
cancelButtonColor: args.cancelButtonColor ? args.cancelButtonColor : '#d33',
showCancelButton: args.showCancelButton === undefined ? false : args.showCancelButton,
showCloseButton: args.showCloseButton === undefined ? false : args.showCloseButton,
showConfirmButton: args.showConfirmButton === undefined ? true : args.showConfirmButton,
didOpen: args.didOpen ? args.didOpen : null,
reverseButtons: true,
}).then((result) => {
if (result['isConfirmed']) {
args.callback ? args.callback_args ? args.callback(args.callback_args) : args.callback() : null;
} else if (result['isDismissed'] && args['isDismissed']) {
event.preventDefault();
args.isDismissed ? args.isDismissed() : null;
}
});
}
The above code block is a general alert display function. I can display alerts based on the parameters I give in "args".
I wrote the following code blocks to show a loading alert when the user clicks a button:
show_alert({
'title': 'Please wait',
'html': 'Loading audio file ...',
'allowEscapeKey': false,
'allowOutsideClick': false,
'showConfirmButton': false,
'showCancelButton': false,
'showCloseButton': false,
'didOpen': () => {Swal.showLoading();},
'isDismissed': () => {console.log('dismissed');}
});
However, when the user clicks anywhere on the page outside of the alert, the alert closes.
Is it possible to stop this by using a function like event.preventDefault()? If you can help, I would appreciate it.
In the "else if" block, I tried to catch the event and prevent the click event, like the "allowOutsideClick" property, but I couldn't.

You ternary always sets allowOutsideClick to a truthy value:
allowOutsideClick: args.allowOutsideClick ? args.allowOutsideClick : true
This needs to be changed to false if allowOutsideClick is falsy:
allowOutsideClick: args.allowOutsideClick ? args.allowOutsideClick : false
As SweetAlert accepts truthy/falsy values for its options, this can be simplified to just:
allowOutsideClick: args.allowOutsideClick
I would recommend looking at your other options and providing similar optimisations. Such as with the allowEscapeKey option (which seems to have a similar issue).
Also, anywhere that you have the pattern of:
a ? a : b
can be simplified to just
a || b
As these mean the same thing.
function show_alert(args) {
Swal.fire({
icon: args.icon,
title: args.title,
text: args.message,
html: args.html,
allowEscapeKey: args.allowEscapeKey,
allowOutsideClick: args.allowOutsideClick,
confirmButtonText: args.confirmButtonText || 'Tamam',
confirmButtonColor: args.confirmButtonColor || '#3085d6',
cancelButtonText: args.cancelButtonText || 'İptal',
cancelButtonColor: args.cancelButtonColor || '#d33',
showCancelButton: args.showCancelButton,
showCloseButton: args.showCloseButton,
showConfirmButton: args.showConfirmButton === undefined ? true : args.showConfirmButton,
didOpen: args.didOpen,
reverseButtons: true,
}).then((result) => {
if (result['isConfirmed']) {
args.callback ? args.callback_args ? args.callback(args.callback_args) : args.callback() : null;
} else if (result['isDismissed'] && args['isDismissed']) {
event.preventDefault();
args.isDismissed ? args.isDismissed() : null;
}
});
}
show_alert({
'title': 'Please wait',
'html': 'Loading audio file ...',
'allowEscapeKey': false,
'allowOutsideClick': false,
'showConfirmButton': false,
'showCancelButton': false,
'showCloseButton': false,
'didOpen': () => {
Swal.showLoading();
},
'isDismissed': () => {
console.log('dismissed');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.6.16/sweetalert2.min.js" integrity="sha512-4aFcnPgoxsyUPgn8gNinplVIEoeBizjYPTpmOaUbC3VZQCsRnduAOch9v0Pn30yTeoWq1rIZByAE4/Gg79VPEA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/11.6.16/sweetalert2.css" integrity="sha512-JzSVRb7c802/njMbV97pjo1wuJAE/6v9CvthGTDxiaZij/TFpPQmQPTcdXyUVucsvLtJBT6YwRb5LhVxX3pQHQ==" crossorigin="anonymous" referrerpolicy="no-referrer"/>
As a side note, you're misusing the conditional operator ? : within your .then(). You should use these when you need to use the return value that the expression evaluates to. When you don't use the evaluated value, and instead just perform side-effects, such as calling a function, then you're better off using an if-statement.
I'd also argue that only calling args.callback(args.callback_args) only when args.callback_args is truthy probably isn't what youu want to do, as this prevents you from being able to specify callback_args as falsy values such as false, 0, "", etc. You're better of always calling args.callback(args.callback_args)

Related

How do I show one swal at the time in javascript

I created a swal for a notification. To show up in the screen the result of the ajax function has to be 0. But this ajax function run every 2 seconds. Sometimes the ajax function returns more than one result has 0, so the swal dont stop showing, just showing the other when the user click in the close button. I would like to show one swal at the time, but setInterval function isnt alowing me to do it.
This is the funtion with the swal:
function montarModalLigacao(cdRamalLigacao = null)
{
var dsHtml = buscaDadosAjax('Ramal', 'obtemHtmlLigacao', {cdLigacaoRamal: cdRamalLigacao});
console.log(dsHtml);
if (dsHtml)
{
swal({
allowOutsideClick: false,
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
title: 'Recebendo Chamada',
html: dsHtml,
cancelButtonText:'Fechar',
confirmButtonText: 'Lançar Ticket',
width: '80%'
}).then((result) => {
if (result.value)
pop_open('man_atendimento_ticket.php?f_id_retorno=70&f_cd_ticket=');
});
}
}
And here is where i call it, with the setInterval:
$(document).ready(function(){
setInterval(function(){
retorno = buscaDadosAjax('Ramal', 'verificarLigacao', {});
if (parseInt(retorno.id_capturado) === 0)
montarModalLigacao(retorno.cd_ramal_ligacao);
}, 2000);
}
Do not do it on an interval, call it when you are ready for the next one to happen.
function montarModalLigacao(cdRamalLigacao = null) {
var dsHtml = buscaDadosAjax('Ramal', 'obtemHtmlLigacao', {
cdLigacaoRamal: cdRamalLigacao
});
console.log(dsHtml);
if (dsHtml) {
swal({
allowOutsideClick: false,
allowEnterKey: false,
showCloseButton: true,
showCancelButton: true,
title: 'Recebendo Chamada',
html: dsHtml,
cancelButtonText: 'Fechar',
confirmButtonText: 'Lançar Ticket',
width: '80%'
}).then((result) => {
if (result.value)
pop_open('man_atendimento_ticket.php?f_id_retorno=70&f_cd_ticket=');
setUpCall();
});
} else {
setUpCall();
}
}
function setUpCall() {
setTimeout(function() {
retorno = buscaDadosAjax('Ramal', 'verificarLigacao', {});
if (parseInt(retorno.id_capturado) === 0)
montarModalLigacao(retorno.cd_ramal_ligacao);
}, 2000);
}
$(document).ready(setUpCall);

I want Sweet alert to work first to change the check to true, false, what to do? [duplicate]

This question already has answers here:
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 2 years ago.
I want Sweet alert to work first to change the check to true, false, what to do? Please help me !
$("#our-table").on('click', '#button-delete', function () {
var check = null;
Swal.fire({
title: 'Are you sure ?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Comfirm'
}).then((result) => {
if (result.isConfirmed) {
check == true
}
})
if (check == true) {
return true;
}
else {
return false;
}
});
Firstly if you want to return true or false according to sweetalert's confirmation, you can pass a callback function and return the checked value in this way:
function sweetChecked(callback) {
Swal.fire({
title: 'Are you sure ?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Comfirm'
}).then((result) => {
callback(result.isConfirmed);
})
}
$("#button-delete").on('click', function (event) {
event.preventDefault();
var URLToRedirect = event.currentTarget.getAttribute('href');
console.log(URLToRedirect);
sweetChecked(function (checked) {
if (checked) {
console.log("true");
window.location.href = URLToRedirect;
}
else {
console.log("false");
}
});
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2#10.12.5/dist/sweetalert2.all.min.js"></script>
<a id="button-delete" href="/ManageUser/Delete/01">Delete</a>
Think the only thing you need to change is
if (result.isConfirmed) {
check = true
}
The == is actually doing a check instead of an assignment.

Observe sweetalert2 confirm with javascript in R Shiny

I have switched to sweetalert2 since the old version is more limited than the new version which is actively developped.
I am running into a problem however, the code I used to observe confirm or cancel in the old version is not working for me anymore.
In the old version I used to add a function in the 'myjava' code after
closeOnConfirm: true}
namely:
,
evalFunction = function(isConfirm){
if (isConfirm === true) {
var val1= 1;
Shiny.onInputChange('option1', [val1, Math.random()]);
}
else {
var val2= 2;
Shiny.onInputChange('option2'', [val2, Math.random()]);
}
}
but that doesn't work with sweetalert2 it seems.
I tried to try and make the examples on the site work but no luck. https://sweetalert2.github.io/
They use a structure like :
.then((result) => {
if (result.value === true) {
swal('Processing');
}
});
but it keeps resulting in a
Warning: Error in : shinyjs: Error parsing the JavaScript file: SyntaxError: Unexpected token >.
Here is the app to test it with. You will need to change the directory and download the two files to make sweetalert2 work
here: https://www.jsdelivr.com/package/npm/sweetalert2
download button is on the right of the title sweetalert2
and the 2 files needed are in the dist folder named:
sweetalert2.min.js & sweetalert2.min.css
setwd('FOLDER WHERE THE sweetalert2files are ')
library(shiny)
library(shinyjs)
myjava <- "shinyjs.swalFromButton = function(params) {
var defaultParams = {
title : null,
html : null
};
params = shinyjs.getParams(params, defaultParams);
swal({title : params.title, html : params.html,
showConfirmButton : true,
confirmButtonText : 'Left',
confirmButtonColor: '#00cc00',
showCancelButton : true,
cancelButtonText : 'Right',
cancelButtonColor : '#339fff',
closeOnCancel : true,
allowOutsideClick: true,
allowEscapeKey: true,
closeOnConfirm: true});
};"
ui <- fluidPage(
actionButton(inputId = 'messagebutton', label = 'click me'),
shinyjs::useShinyjs(),
shinyjs::extendShinyjs(text = myjava),
tags$head(includeScript("sweetalert2.min.js"),
includeCSS("sweetalert2.min.css")
)
)
server <- function(input, output, session) {
observeEvent(input$messagebutton, {
shinyjs::js$swalFromButton( title = paste('<span style ="color:#339FFF;">An alert with a choice'),
html = paste('Pick left or right'))
})
observeEvent(input$option1, { print('confirm choosen')})
observeEvent(input$option2, { print('cancel choosen')})
}
shinyApp(ui = ui, server = server)
UPDATE
I tried endless variations of this javascript, removing the problematic > symbol as was suggested, but R keeps throwing 'error parsing the javascript code provided.
myjava <- "shinyjs.swalFromButton = function(params) {
var defaultParams = {
title : null,
html : null
};
params = shinyjs.getParams(params, defaultParams);
swal({title : params.title, html : params.html,
showConfirmButton : true,
confirmButtonText : 'Left',
confirmButtonColor: '#00cc00',
showCancelButton : true,
cancelButtonText : 'Right',
cancelButtonColor : '#339fff',
closeOnCancel : true,
allowOutsideClick: true,
allowEscapeKey: true,
closeOnConfirm: true}).then((result){
if (result.value === true) {
swal('Processing');
}
});
};"
Thanks to Stéphane Laurents comments, this is the solution:
Including the means to send a variable back to R shiny.
myjava <- "shinyjs.swalFromButton = function(params) {
var defaultParams = {
title : null,
html : null
};
params = shinyjs.getParams(params, defaultParams);
swal({title : params.title, html : params.html,
showConfirmButton : true,
confirmButtonText : 'Left',
confirmButtonColor: '#00cc00',
showCancelButton : true,
cancelButtonText : 'Right',
cancelButtonColor : '#339fff',
closeOnCancel : true,
allowOutsideClick: true,
allowEscapeKey: true,
closeOnConfirm: true})
.then(function(result){
swal('succes');
if (result.value === true) {
var val1= true;
Shiny.setInputValue('option1', val1, {priority: "event"});}
else {
swal('failure');
var val2= true;
Shiny.setInputValue('option2', val2, {priority: "event"});}
});
};"

Delay appearance of buttons in sweetalert2

I am using SweetAlert2 to communicate some feedback to the user. This is a learning app, so, I want the feedback to persist for some time. I do not want to show any buttons immediately after the feedback is displayed because people have a tendency to just click on 'OK' or 'Cancel', without reading the text.
The number of characters in the feedback varies from screen to screen, so, I am using the timer parameter of sweetalert2 to be some multiple of the number of characters in the text. But, the timer feature is imperfect because people have different reading speeds. Ideally, I would want the 'OK' button to appear after the timer has timed out. Is there some sort of an API call I can make to dynamically change the property of the alert box?
swal({
html: feedback,
timer: feedback.length*50,
showCloseButton: false,
showCancelButton: false,
showConfirmButton: false,
allowOutsideClick: false,
});
I don't see any method to hide and show the buttons, but you can disable and enable them:
swal({
html: 'test',
allowOutsideClick: false,
allowEscapeKey: false,
onOpen: function () {
swal.disableButtons();
setTimeout(swal.enableButtons, 'test'.length * 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
or make them transparent:
swal({
html: 'test',
allowOutsideClick: false,
allowEscapeKey: false,
onOpen: function () {
var b = swal.getConfirmButton()
b.style.opacity = 0
b.disabled = true
setTimeout(function() {
b.disabled = false
b.style.opacity = 1
}, 'test'.length * 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
or hide and show:
swal({
html: 'test',
allowOutsideClick: false,
allowEscapeKey: false,
onOpen: function () {
var b = swal.getConfirmButton()
b.hidden = true
b.disabled = true
setTimeout(function() {
b.disabled = false
b.hidden = false
}, 'test'.length * 500)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.min.css">
Hi to achive this you can use a set timeout function and call jQuery's .show() function on the buttons that you wish to show (Assuming you are ok with using jQuery).
The following code should help you out
swal({
html: feedback,
timer: feedback.length*50,
showCloseButton: false,
showCancelButton: false,
showConfirmButton: false,
allowOutsideClick: false,
});
setTimeout(function () {
$(".swal2-cancel").show();
$(".swal2-confirm").show();
$(".swal2-close").show();
}, 3000);
Hope this helps :-)

Timer with confirm and cancel button

i'm a noobs at sweet alert.
Is it possible to create a sweet alert prompt which has confirm button, cancel and timer.
The logic is if the alert not confirmed, timer automatically execute the same function with cancel. I have tried and stuck. even if the alert confirmed, the timer still counting and the the cancel function is called.
sweetAlert({
title: 'Stay in fullscreen',
text: "You will be logged out in 10 seconds or if you leave the fullscreen!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#ff0000',
confirmButtonText: 'Go fullscreen!',
cancelButtonText: 'Leave this page!',
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-warning',
closeOnConfirm: 'true',
timer:'10000',
buttonsStyling: false
},function(isConfirm) {
if (isConfirm) {
return launchIntoFullscreen(document.documentElement) // timer still still counting
} else {
return Redirect()
}
}).then(function () {
swal(
window.alert('teest')
)
}, function (dismiss) {
// dismiss can be 'cancel', 'overlay',
// 'close', and 'timer'
if (dismiss === 'timer') {
return Redirect()
}
})
Checking the isConfirm argument for null should tell you if the callback was initialized by the timer finishing.
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: true,
showCancelButton: true
},
function(isConfirm) {
if (isConfirm === null || isConfirm == false)
cancelFunction();
else
confirmFunction();
}
);
As far as I could find, this behavior is not documented, but I believe this is the relevant bit of the source
swal({
title: "Auto close alert!",
text: "I will close in 2 seconds.",
timer: 2000,
showConfirmButton: true,
showCancelButton: true
},
function(isConfirm) {
if (isConfirm === null || isConfirm == false)
cancelFunction();
else
confirmFunction();
}
);
the code above still execute cancelFunction();
i add a line before Confirmfunction.
if (isConfirm !=null && isConfirm != false) {
closeInSeconds = Number.MAX_VALUE/1000; // this line extends timer time
document.documentElement);
}
else {
Redirect();
}

Categories

Resources