I am using SweetAlert and I have custom buttons like this example:
swal("A wild Pikachu appeared! What do you want to do?", {
buttons: {
cancel: "Run away!",
catch: {
text: "Throw Pokéball!",
value: "catch",
},
defeat: true,
},
onOpen: function() { console.log("Test") } // this doesn't work
})
.then((value) => { ... });
However, on initial opening, it's focusing to the last button. Is there a way to cancel this auto-focus pletely so on initial opening, it doesn't focus on any button?
I am using SweetAlert and I have custom buttons like this example:
swal("A wild Pikachu appeared! What do you want to do?", {
buttons: {
cancel: "Run away!",
catch: {
text: "Throw Pokéball!",
value: "catch",
},
defeat: true,
},
onOpen: function() { console.log("Test") } // this doesn't work
})
.then((value) => { ... });
However, on initial opening, it's focusing to the last button. Is there a way to cancel this auto-focus pletely so on initial opening, it doesn't focus on any button?
Share Improve this question edited Jul 7, 2018 at 14:34 Limon Monte 54.4k49 gold badges188 silver badges219 bronze badges asked Jul 6, 2018 at 22:08 sentysenty 12.9k29 gold badges140 silver badges267 bronze badges 4-
The
onOpen
event not available on SweetAlert. You could use SweetAlert2 instead sweetalert2.github.io – mul14 Commented Jul 6, 2018 at 23:51 - Yeah, just noticed that after everything was done in the project :(. Would everything work same way if I just change the npm package? Or is swal2 a plete rewrite? – senty Commented Jul 7, 2018 at 18:19
- They are different packages with different APIs. – mul14 Commented Jul 9, 2018 at 0:09
- This publication served me as it provides a clear example Show SweetAlert2 over Bootstrap modal – Gustavo Commented Nov 11, 2019 at 18:39
2 Answers
Reset to default 6As already suggested in ments, SweetAlert2 is more flexible solution, I remend using it.
With didOpen
parameter and getConfirmButton()
method you can achieve the desired behavior:
Swal.fire({
input: 'text',
inputPlaceholder: 'I will not be autofocuses',
didOpen: () => Swal.getConfirmButton().focus()
})
<script src="https://cdn.jsdelivr/npm/sweetalert2@11"></script>
We can use didOpen
and blur
:
<script src="https://cdn.jsdelivr/npm/sweetalert2@11"></script>
<script>
Swal.fire({
html: "<b style='color: red;'>Remove</b> button focus!<br>Press ENTER to check.",
didOpen: function () {
Swal.getConfirmButton().blur()
}
});
</script>