How to use sweetalert2

By FoxLearn 7/19/2024 3:01:36 AM   10.4K
Sweetalert2 is a beautiful popup boxes helps you easily show a message box in your website.

To use SweetAlert2, a JavaScript library for creating beautiful, customizable, and responsive modal dialogs, follow these steps:

You can include SweetAlert2 in your project by either downloading the files from the official website or using a package manager like npm or yarn.

npm install sweetalert2
yarn add sweetalert2

Alternatively, you can include it directly from a CDN

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@latest"></script>

Another way, you can download and install Sweetalert2 at github

If you wan to download it directly from cdnjs in your Visual Studio.

Right-clicking on your folder you need to install, then select Add =>Client-Side Library...

cdnjs sweetalert2

To use SweetAlert2, follow these steps

Creating a html page, then modify your code as shown below.

If you're using a module bundler like webpack or Parcel, you can import SweetAlert2 into your project like this:

import Swal from 'sweetalert2';

If you're not using a module bundler, you can include SweetAlert2 directly via a <script> tag in your HTML file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="lib/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="lib/limonte-sweetalert2/sweetalert2.min.css" />
</head>
<body>
    <button class="btn btn-primary" aria-label="Try me! Example: A basic message" onclick="message()">
        Try me!
    </button>
    <script src="lib/jquery/dist/jquery.min.js"></script>
    <script src="lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
    <script src="lib/limonte-sweetalert2/sweetalert2.all.min.js"></script>
    <script type="text/javascript">
        function message() {
            Swal.fire({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!'
            }).then((result) => {
                if (result.value) {
                    Swal.fire(
                        'Deleted!',
                        'Your file has been deleted.',
                        'success'
                    )
                }
            });
        }
    </script>
</body>
</html>

You can use SweetAlert2 to display alerts, prompts, confirmations, and more.

Here are some examples:

You can display a simple modal dialog by calling the Swal.fire() function:

Swal.fire('Welcome to FoxLearn !')

sweetalert2 tutorial

SweetAlert2 allows you to customize various aspects of the dialog, such as title, text, icon, buttons, etc.

Sweetalert2 display a title with a text under

Swal.fire(
  'Enter your title',
  'Enter your message',
  'question'
)

sweetalert2

Sweetalert2 display a modal with a title, an error icon, a text, and a footer

Swal.fire({
  icon: 'error',
  title: 'Enter your title here',
  text: 'Enter your message here',
  footer: '<a href>http://foxlearn.com</a>'
})

sweetalert2

Sweetalert2 display a modal window with a long content inside

Swal.fire({
  imageUrl: 'Your image url',
  imageHeight: 1500,
  imageAlt: 'Your alt image'
})

Sweetalert2 with a custom HTML description and buttons with ARIA labels

Swal.fire({
  title: 'Your html title',
  icon: 'info',
  html: 'Your html content',
  showCloseButton: true,
  showCancelButton: true,
  focusConfirm: false,
  confirmButtonText: 'Your html button text',
  confirmButtonAriaLabel: 'Thumbs up',
  cancelButtonText:'Your html button text',
  cancelButtonAriaLabel: 'Thumbs down'
})

sweetalert2

Sweetalert2 with a custom positioned dialog

Swal.fire({
  position: 'top-end',
  icon: 'success',
  title: 'Your work has been saved',
  showConfirmButton: false,
  timer: 1500
})

Sweetalert2  with custom animation with Animate.css

Swal.fire({
  title: 'Custom animation with Animate.css',
  showClass: {
    popup: 'animated fadeInDown faster'
  },
  hideClass: {
    popup: 'animated fadeOutUp faster'
  }
})

Sweetalert2 display a confirm dialog, with a function attached to the "Confirm"-button

Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.value) {
    Swal.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  }
})

sweetalert2

Sweetalert2 passing a parameter, then you can execute something else for "Cancel"

const swalWithBootstrapButtons = Swal.mixin({
  customClass: {
    confirmButton: 'btn btn-success',
    cancelButton: 'btn btn-danger'
  },
  buttonsStyling: false
})

swalWithBootstrapButtons.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, cancel!',
  reverseButtons: true
}).then((result) => {
  if (result.value) {
    swalWithBootstrapButtons.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  } else if (
    /* Read more about handling dismissals below */
    result.dismiss === Swal.DismissReason.cancel
  ) {
    swalWithBootstrapButtons.fire(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

Sweetalert2 display a message with a custom image

Swal.fire({
  title: 'Sweet!',
  text: 'Modal with a custom image.',
  imageUrl: 'https://unsplash.it/400/200',
  imageWidth: 400,
  imageHeight: 200,
  imageAlt: 'Custom image',
})

sweetalert2

Sweetalert2 display a message with custom width, padding, background and animated Nyan Cat

Swal.fire({
  title: 'Custom width, padding, background.',
  width: 600,
  padding: '3em',
  background: '#fff url(/images/trees.png)',
  backdrop: `
    rgba(0,0,123,0.4)
    url("/images/nyan-cat.gif")
    left top
    no-repeat
  `
})

Sweetalert2 display a message with auto close timer

let timerInterval
Swal.fire({
  title: 'Auto close alert!',
  html: 'I will close in <b></b> milliseconds.',
  timer: 2000,
  timerProgressBar: true,
  onBeforeOpen: () => {
    Swal.showLoading()
    timerInterval = setInterval(() => {
      const content = Swal.getContent()
      if (content) {
        const b = content.querySelector('b')
        if (b) {
          b.textContent = Swal.getTimerLeft()
        }
      }
    }, 100)
  },
  onClose: () => {
    clearInterval(timerInterval)
  }
}).then((result) => {
  /* Read more about handling dismissals below */
  if (result.dismiss === Swal.DismissReason.timer) {
    console.log('I was closed by the timer')
  }
})

Sweetalert2 with Right-to-left for Arabic, Persian, Hebrew, and other RTL languages

Swal.fire({
  title: 'هل تريد الاستمرار؟',
  icon: 'question',
  iconHtml: '؟',
  confirmButtonText: 'نعم',
  cancelButtonText: 'لا',
  showCancelButton: true,
  showCloseButton: true
})

Sweetalert2 AJAX request example

Swal.fire({
  title: 'Submit your Github username',
  input: 'text',
  inputAttributes: {
    autocapitalize: 'off'
  },
  showCancelButton: true,
  confirmButtonText: 'Look up',
  showLoaderOnConfirm: true,
  preConfirm: (login) => {
    return fetch(`//api.github.com/users/${login}`)
      .then(response => {
        if (!response.ok) {
          throw new Error(response.statusText)
        }
        return response.json()
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.value) {
    Swal.fire({
      title: `${result.value.login}'s avatar`,
      imageUrl: result.value.avatar_url
    })
  }
})

sweetalert2

Sweetalert2 chaining modals (queue) example

Swal.mixin({
  input: 'text',
  confirmButtonText: 'Next &rarr;',
  showCancelButton: true,
  progressSteps: ['1', '2', '3']
}).queue([
  {
    title: 'Question 1',
    text: 'Chaining swal2 modals is easy'
  },
  'Question 2',
  'Question 3'
]).then((result) => {
  if (result.value) {
    const answers = JSON.stringify(result.value)
    Swal.fire({
      title: 'All done!',
      html: `
        Your answers:
        <pre><code>${answers}</code></pre>
      `,
      confirmButtonText: 'Lovely!'
    })
  }
})

sweetalert2

Sweetalert2 Dynamic queue example

const ipAPI = '//api.ipify.org?format=json'

Swal.queue([{
  title: 'Your public IP',
  confirmButtonText: 'Show my public IP',
  text:
    'Your public IP will be received ' +
    'via AJAX request',
  showLoaderOnConfirm: true,
  preConfirm: () => {
    return fetch(ipAPI)
      .then(response => response.json())
      .then(data => Swal.insertQueueStep(data.ip))
      .catch(() => {
        Swal.insertQueueStep({
          icon: 'error',
          title: 'Unable to get your public IP'
        })
      })
  }
}])

sweetalert2

Sweetalert2 is the 34th most popular package on jsDelivr. It provides additional features like input fields, AJAX requests, timers, etc

You can customize the appearance of SweetAlert2 dialogs using CSS. The library provides default styles, but you can override them to match your application's design.

These are just some basic examples. SweetAlert2 offers many more customization options, such as customizing buttons, adding custom HTML content, styling, animations, etc