A zero dependencies beautiful, responsive, customizable, accessible (WAI-ARIA) replacement for JavaScript’s popup boxes
Installation
You can install SweetAlerts2 via npm
1 |
npm install sweetalert2 |
or by you can grab it via jsdeliver CDN
1 |
Usage
1. Initialize the plugin by referencing the necessary files:
1 2 3 |
<span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"sweetalert2.all.min.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-comment"><!-- Optional: include a polyfill for ES6 Promises for IE11 --></span> <span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/promise-polyfill"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> |
You can also include the stylesheet separately if desired:
1 2 |
<span class="hljs-tag"><<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"sweetalert2.min.js"</span>></span><span class="hljs-tag"></<span class="hljs-name">script</span>></span> <span class="hljs-tag"><<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"sweetalert2.min.css"</span>></span> |
Or
1 2 3 4 5 |
<span class="hljs-comment">// ES6 Modules or TypeScript</span> <span class="hljs-keyword">import</span> Swal <span class="hljs-keyword">from</span> <span class="hljs-string">'sweetalert2'</span> <span class="hljs-comment">// CommonJS</span> <span class="hljs-keyword">const</span> Swal = <span class="hljs-built_in">require</span>(<span class="hljs-string">'sweetalert2'</span>) |
It’s possible to import JS and CSS separately, e.g. if you need to customize styles:
1 2 3 |
<span class="hljs-keyword">import</span> Swal <span class="hljs-keyword">from</span> <span class="hljs-string">'sweetalert2/dist/sweetalert2.js'</span> <span class="hljs-keyword">import</span> <span class="hljs-string">'sweetalert2/src/sweetalert2.scss'</span> |
2. Call the sweetAlert2-function after the page has loaded
1 2 3 4 5 6 |
Swal.fire({ <span class="hljs-attr">title</span>: <span class="hljs-string">'Error!'</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Do you want to continue'</span>, <span class="hljs-attr">icon</span>: <span class="hljs-string">'error'</span>, <span class="hljs-attr">confirmButtonText</span>: <span class="hljs-string">'Cool'</span> }) |
You can go to the official library site to see Alerts Examples, by clicking on this link.