SweetAlert2 – Awesome Library Solution for Old Javascript Alert Popups

SweetAlert2 – Awesome Library Solution for Old Javascript Alert Popups

Welcome Folks I am back with another interesting post. In this post we will be talking about a Awesome Library for making Plain old Javascript Popups more interactive and appealing. The library name is SweetAlert2. It’s a Open Source Library and you can use this library in your projects to replace the old fashion popups.

 

 

alert('You clicked the button!')

 

 

Swal.fire(
  'Good job!',
  'You clicked the button!',
  'success'
)

 

Download and Install

 

 

npm install sweetalert2

 

Grab from jsdelivr CDN

 

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

 

Usage

 

<script src="sweetalert2.all.min.js"></script>
<!-- Optional: include a polyfill for ES6 Promises for IE11 and Android browser -->
<script src="https://cdn.jsdelivr.net/npm/promise-polyfill"></script>

 

 

You can also include stylesheet and js files separately

 

<script src="sweetalert2.min.js"></script>
<link rel="stylesheet" href="sweetalert2.min.css">

 

// ES6 Modules or TypeScript
import Swal from 'sweetalert2'

// CommonJS
const Swal = require('sweetalert2')

 

import Swal from 'sweetalert2/dist/sweetalert2.js'

import 'sweetalert2/src/sweetalert2.scss'

 

Call Swal function after Page has been loaded

Swal.fire({
  title: 'Error!',
  text: 'Do you want to continue',
  type: 'error',
  confirmButtonText: 'Cool'
})

 

SweetAlert 2 Mixin Example

 

const Toast = Swal.mixin({
  toast: true,
  position: 'top-end',
  showConfirmButton: false,
  timer: 3000
});

Toast.fire({
  type: 'success',
  title: 'Signed in successfully'
})

 

 

Popups Alert Types

 

Error

 

 

Warning

 

 

Info

 

 

Success

 

Question

 

 

Examples

 

Input Alert Popup

 

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

const inputValue = fetch(ipAPI)
  .then(response => response.json())
  .then(data => data.ip)

const {value: ipAddress} = await Swal.fire({
  title: 'Enter your IP address',
  input: 'text',
  inputValue: inputValue,
  showCancelButton: true,
  inputValidator: (value) => {
    if (!value) {
      return 'You need to write something!'
    }
  }
})

if (ipAddress) {
  Swal.fire(`Your IP address is ${ipAddress}`)
}

 

 

Input Email Alert Popup

 

const {value: email} = await Swal.fire({
  title: 'Input email address',
  input: 'email',
  inputPlaceholder: 'Enter your email address'
})

if (email) {
  Swal.fire('Entered email: ' + email)
}

 

READ  Make a Fully Responsive Website in Materialize CSS with Source Code in 2019

 

Input URL Alert Popup

 

const {value: url} = await Swal.fire({
  input: 'url',
  inputPlaceholder: 'Enter the URL'
})

if (url) {
  Swal.fire('Entered URL: ' + url)
}

 

 

Password Input Alert Popup

 

 

TextArea Input Alert Popup

 

const {value: text} = await Swal.fire({
  input: 'textarea',
  inputPlaceholder: 'Type your message here...',
  showCancelButton: true
})

if (text) {
  Swal.fire(text)
}

 

 

Select Alert Input Popup

 

const {value: fruit} = await Swal.fire({
  title: 'Select field validation',
  input: 'select',
  inputOptions: {
    'apples': 'Apples',
    'bananas': 'Bananas',
    'grapes': 'Grapes',
    'oranges': 'Oranges'
  },
  inputPlaceholder: 'Select a fruit',
  showCancelButton: true,
  inputValidator: (value) => {
    return new Promise((resolve) => {
      if (value === 'oranges') {
        resolve()
      } else {
        resolve('You need to select oranges :)')
      }
    })
  }
})

if (fruit) {
  Swal.fire('You selected: ' + fruit)
}

 

 

Radio Button Input Alert Popup

 

// inputOptions can be an object or Promise
const inputOptions = new Promise((resolve) => {
  setTimeout(() => {
    resolve({
      '#ff0000': 'Red',
      '#00ff00': 'Green',
      '#0000ff': 'Blue'
    })
  }, 1000)
})

const {value: color} = await Swal.fire({
  title: 'Select color',
  input: 'radio',
  inputOptions: inputOptions,
  inputValidator: (value) => {
    if (!value) {
      return 'You need to choose something!'
    }
  }
})

if (color) {
  Swal.fire({html: 'You selected: ' + color})
}

 

 

Checkbox Input Alert Popup

 

const {value: accept} = await Swal.fire({
  title: 'Terms and conditions',
  input: 'checkbox',
  inputValue: 1,
  inputPlaceholder:
    'I agree with the terms and conditions',
  confirmButtonText:
    'Continue <i class="fa fa-arrow-right></i>',
  inputValidator: (result) => {
    return !result && 'You need to agree with T&C'
  }
})

if (accept) {
  Swal.fire('You agreed with T&C :)')
}

 

 

File Input Alert Popup

 

const {value: file} = await Swal.fire({
  title: 'Select image',
  input: 'file',
  inputAttributes: {
    'accept': 'image/*',
    'aria-label': 'Upload your profile picture'
  }
})

if (file) {
  const reader = new FileReader
  reader.onload = (e) => {
    Swal.fire({
      title: 'Your uploaded picture',
      imageUrl: e.target.result,
      imageAlt: 'The uploaded picture'
    })
  }
  reader.readAsDataURL(file)
}

 

READ  jQuery Plugin To Display Photos From Your Facebook Album - Facebook Photos

 

Range Input Alert Popup

 

Swal.fire({
  title: 'How old are you?',
  type: 'question',
  input: 'range',
  inputAttributes: {
    min: 8,
    max: 120,
    step: 1
  },
  inputValue: 25
})

 

 

Multiple Inputs Alert Popup

 

const {value: formValues} = await Swal.fire({
  title: 'Multiple inputs',
  html:
    '<input id="swal-input1" class="swal2-input">' +
    '<input id="swal-input2" class="swal2-input">',
  focusConfirm: false,
  preConfirm: () => {
    return [
      document.getElementById('swal-input1').value,
      document.getElementById('swal-input2').value
    ]
  }
})

if (formValues) {
  Swal.fire(JSON.stringify(formValues))
}

 

 

More Examples

 

Swal.fire({
  type: 'error',
  title: 'Oops...',
  text: 'Something went wrong!',
  footer: '<a href>Why do I have this issue?</a>'
})

 

 

Swal.fire({
  title: '<strong>HTML <u>example</u></strong>',
  type: 'info',
  html:
    'You can use <b>bold text</b>, ' +
    '<a href="//github.com">links</a> ' +
    'and other HTML tags',
  showCloseButton: true,
  showCancelButton: true,
  focusConfirm: false,
  confirmButtonText:
    '<i class="fa fa-thumbs-up"></i> Great!',
  confirmButtonAriaLabel: 'Thumbs up, great!',
  cancelButtonText:
    '<i class="fa fa-thumbs-down"></i>',
  cancelButtonAriaLabel: 'Thumbs down',
})

 

 

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

 

 

Swal.fire({
  title: 'Custom animation with Animate.css',
  animation: false,
  customClass: {
    popup: 'animated tada'
  }
})

 

 

Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: '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'
    )
  }
})

 

 

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!",
  type: '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
    result.dismiss === Swal.DismissReason.cancel
  ) {
    swalWithBootstrapButtons.fire(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

 

READ  React File Uploader With Express (Using React Hooks)

 

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

 

 

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")
    center left
    no-repeat
  `
})

 

 

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

 

 

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

 

 

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
    })
  }
})

 

 

Swal.mixin({
  input: 'text',
  confirmButtonText: 'Next →',
  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) {
    Swal.fire({
      title: 'All done!',
      html:
        'Your answers: <pre><code>' +
          JSON.stringify(result.value) +
        '</code></pre>',
      confirmButtonText: 'Lovely!'
    })
  }
})

 

 

Leave a Reply

Close Menu