Good day, I am trying to use sweetalert onclick but when I click on the button nothing happens, only the alert is displayed when refreshing the page, what I want to achieve is that when clicking on the button the alert appears, not when refreshing the page.
I am trying to use sweetalert, it is supposed that when I click on a button should appear the alert but this does not happen in fact, at startup it appears automatically every time I load the page, what I want to achieve is that only when I click on the button the alert appears, not every time the page is refreshed.
function successAlert()
Swal.fire(
'saved!',
'success'
)
.show-example-btn {
font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
<script src="sweetalert2.min.js"></script>
<link rel="stylesheet" href="sweetalert2.min.css">
<div class="showcase sweet">
<button
class="show-example-btn"
aria-label="Show SweetAlert2 success message"
onclick="successAlert()">
save
</button>
<pre data-example-id="sweetAlert"></pre>
</div>
>Solution :
Bad function definition, missing { and } like Quentin mentioned in the comments and also the structure of a basic swal alert goes like this
Swal.fire(
title,
text,
icon
)
You were adding success message where the text should go and your icon would never show on your alert. You should change it to something like this:
function successAlert() {
Swal.fire(
'saved!',
'You successfully pressed the button',
'success'
)
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<div class="showcase sweet">
<button class="show-example-btn" aria-label="Show SweetAlert2 success message" onclick="successAlert()">
save
</button>
<pre data-example-id="sweetAlert"></pre>
</div>