Sweet Alert 2 - Tutorial con ejemplos - Parzibyte's blog (2024)

Resumen: mostrar una introducción (instalación y uso) a Sweet Alert 2, una librería de JavaScript para mostrar alertas y diálogos de confirmación con un diseño bonito.

Te mostraré cómo descargar SweetAlert 2, además de:

  • Mostrar una alerta
  • Personalizar el contenido
  • Mostrar un diálogo de confirmación y saber respuesta del usuario
  • Diálogo personalizado con HTML
  • Mostrar alerta con input para recoger información

Todo esto usando JavaScript.

Nota: el código mostrado aquí está en GitHub, y la demostración aquí.

Obtener librería Sweet Alert 2

Ve al siguiente enlace:

https://unpkg.com/sweetalert2@9.5.3/dist/sweetalert2.all.min.js

Y descarga el script de JavaScript. También puedes conseguir la última versión en:

https://unpkg.com/sweetalert2

Una vez que lo hayas descargado, incluye el script en el head de tu HTML. El mismo ya tiene el CSS y el JS necesario para usar Sweet Alert 2.

Mostrar alerta simple

Esto es el equivalente o remplazo de la función nativa alert.

El hola mundo de esta librería es así:

Con el siguiente resultado:

Nota: la tipografía del texto es tomada de tu web, es decir, la librería no incluye ninguna tipografía.

Evento de alerta cerrada / aceptada

Si quieres saber cuándo se cierra una alerta (es decir, que se presiona el botón de OK o que se cierra) espera a que se resuelva la promesa que el método fire devuelve, así:

No es lo mismo que un diálogo de confirmación, como veremos más adelante, pero funciona para saber si la alerta se ha cerrado.

Cambiar texto del botón de alerta con Sweet Alert 2

Si no quieres que aparezca el texto “OK” en el botón, puedes invocar a Swal.fire pero con un objeto de propiedades. Solo debes especificar title y confirmButtonText así:

De este modo tendrás una alerta más personalizada:

Título y texto

La alerta también puede mostrar texto, además del título y el botón. Esto se logra especificando title, text y opcionalmente confirmButtonText.

HTML personalizado con Sweet Alert 2

Si las propiedades de title y text no se ajustan a tus necesidades, puedes enviar directamente una cadena HTML usando la propiedad html:

Las comillas que uso son las backticks, no son necesarias para el HTML pero permiten especificar cadenas de múltiples líneas.

Nota: de igual forma puedes seguir personalizando el botón, así como esperar a que la alerta se cierre con la promesa.

Diálogo de confirmación con Sweet Alert 2

Con esta librería de JavaScript puedes mostrar una alerta de confirmación de manera fácil. Se hace así:

Este es el equivalente a la función confirm de JavaScript.

Aquí vemos más opciones al mostrar la alerta. Por ejemplo, tenemos un icon que personaliza el icono. Además, con showCancelButton especificamos que se muestre el botón para cancelar (si no, entonces solo se muestra el que acepta)

La opción cancelButtonText es parecida a confirmButtonText y se encarga de personalizar el título del botón para cancelar.

Finalmente, al resolverse la promesa se resolverá con una variable que tendrá la propiedad value. Si hicieron click en , tendrá el valor de true, y si no, false.

Mostrar un input y recibir el valor

Ya vimos cómo mostrar una alerta y un diálogo de confirmación. Ahora veremos cómo solicitar un valor a través de un input.

Queda así:

Lo que realmente hace que se muestre la caja de texto o input es la propiedad input, que en este caso es de tipo text.

Al resolverse la promesa de la alerta, podremos acceder al valor que el usuario escribió.

Validación de input en Sweet Alert 2

Si quieres validar el campo de texto en donde el usuario escribe, puedes definir la función inputValidator, que recibe el valor y debe regresar undefined o una cadena.

En caso de que regrese una cadena, se mostrará el error y no se procederá. En caso de que regrese undefined (o que simplemente no regrese nada) se supondrá que el valor es válido.

Con el siguiente resultado:

Mis proyectos que usan Sweet Alert 2

Juego de memorama con JavaScript

Software de acortadores

Conclusión

Solo resta dejar el enlace al repositorio de GitHub de esta librería; no olvides que puedes visitar la documentación oficial para afinar detalles de su uso.

Te invito a leer más sobre JavaScript en mi blog.

El código mostrado aquí está en GitHub, y la demostración aquí.

Estoy aquí para ayudarte en todo lo que necesites. Si requieres alguna modificación en lo presentado en este post, deseas asistencia con tu tarea, proyecto o precisas desarrollar un software a medida, no dudes en contactarme. Estoy comprometido a brindarte el apoyo necesario para que logres tus objetivos. Mi correo es parzibyte(arroba)gmail.com, estoy como@parzibyte en Telegram o en mi página de contacto

No te pierdas ninguno de mis posts 🚀🔔

Suscríbete a mi canal de Telegram para recibir una notificación cuando escriba un nuevo tutorial de programación.

Sweet Alert 2 - Tutorial con ejemplos - Parzibyte's blog (2024)

FAQs

How to use sweet alert in WordPress? ›

  1. Upload cf7-sweet-alert-popup to the /wp-content/plugins/ directory.
  2. Activate the plugin through the \'Plugins\' menu in WordPress.
  3. Ready !
Sep 13, 2023

What is SweetAlert2? ›

SweetAlert2 - a beautiful, responsive, customizable and accessible (WAI-ARIA) replacement for JavaScript's popup boxes.

How to use Swal in HTML? ›

An alert message with a function attached to the "Confirm" button and "cancel" button.
  1. swal({
  2. title: " Confirm?",
  3. text: "Imaginary file",
  4. type: "alert message",
  5. showCancelButton: true,
  6. confirmButtonClass: "btn-danger",
  7. confirmButtonText: " Confirm, remove it!",
  8. closeOnConfirm: false.

What is the alternative to Sweet Alert? ›

sweetalert2 alternatives and similar libraries
  • SweetAlert. 9.2 0.0 L4 sweetalert2 VS SweetAlert. ...
  • Magnific-Popup. 8.6 5.3 L2 sweetalert2 VS Magnific-Popup. ...
  • fancyBox. 7.7 3.9 L1 sweetalert2 VS fancyBox. ...
  • X-editable. 7.4 0.0 L3 sweetalert2 VS X-editable. ...
  • tether. 7.3 8.8 L3 sweetalert2 VS tether. ...
  • lightGallery. ...
  • screenfull.js. ...
  • vex.
Jun 9, 2024

What are the different types of sweet alerts? ›

SweetAlert comes with 4 built-in types which will show a corresponding icon animation: "warning", "error", "success" and "info". You can also set it as "input" to get a prompt modal.

What is the difference between Sweetalert and SweetAlert2? ›

SweetAlert2 is simply a cleaner version. The functions are much easier to use and the documentation provides much more usability, when compared to it's first version. Upon going through the sweetalert upgrade logs, it is recommended to use sweetalert2 because of its easy to use, flexible, awesome new changes.

How to use SweetAlert2 in Django? ›

SweetAlert2 comes with 5 built-in icon which will show a corresponding icon animation: warning , error , success , info , and question . It can either be put in the array under the key “icon” or passed as the third parameter of the function. document. getElementById('errorAlert').

How to implement sweet alert in MVC? ›

Let's start with creating basic MVC project first and then we are going add Sweet Alert inside it. Open Visual Studio IDE on start page and select New Project. After selecting a New Project dialog will appear inside that select Templates Visual C# inside this select Web.

Is SweetAlert2 free? ›

sweetalert2 - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers.

How to use sweet alert in Ajax? ›

Visit this route http://localhost:8000/users and you will see a page like this:
  1. Click Delete button and the SweetAlert2 confirmation box will appear:
  2. Click Yes button, the data will be deleted via AJAX and you will see a confirmation message like this:
Feb 25, 2022

What are the types of icons in SweetAlert2? ›

SweetAlert2 comes with 5 built-in types which will show a corresponding icon animation: warning, error, success, info and question. It can either be put in the array under the key "type" or passed as the third parameter of the function.

How to use SweetAlert2 in React? ›

Create a React.

Open this project in Visual Studio Code and install Bootstrap by using the following command. Now, open the index. js file and add import Bootstrap. Now install sweetalert2 by using the following command.

How to use SweetAlert2 in Laravel? ›

To use SweetAlert2 in your Laravel project, you will need to include the SweetAlert2 JavaScript library and initiate an alert. You can do this in a Laravel blade template using the following steps: In your blade template, make sure you have included the SweetAlert2 JavaScript library.

How do I use alerts in WordPress? ›

Click the Alert Box icon in the Advanced Elements selection tool. Select the Alert Box Type (info, success, warning, error) you want to display. Enter the content you want to display in the editor. Limited options are available in the Alert Box editor, such as bold, italics, underline, and hyperlink.

How do I make text clickable in WordPress? ›

3 Easy Steps to Make a Clickable Link in WordPress
  1. Highlight the text you want to make a clickable link. ...
  2. Click the link icon in your visual editor ( 🔗 ) ...
  3. Paste in your target URL and click “Apply“
Sep 7, 2021

How do I send a comment notification in WordPress? ›

To turn on email notifications for new comments, take the following steps:
  1. Visit your site's dashboard.
  2. Navigate to Settings → Discussion on the left side.
  3. Scroll down to the “E-mail me whenever” section.
  4. Toggle on the option to receive an email when “Anyone posts a comment”.

Top Articles
Latest Posts
Article information

Author: Roderick King

Last Updated:

Views: 6321

Rating: 4 / 5 (71 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Roderick King

Birthday: 1997-10-09

Address: 3782 Madge Knoll, East Dudley, MA 63913

Phone: +2521695290067

Job: Customer Sales Coordinator

Hobby: Gunsmithing, Embroidery, Parkour, Kitesurfing, Rock climbing, Sand art, Beekeeping

Introduction: My name is Roderick King, I am a cute, splendid, excited, perfect, gentle, funny, vivacious person who loves writing and wants to share my knowledge and understanding with you.