آموزش جامع SweetAlert2
جایگزین حرفهای و زیبا برای هشدارهای پیشفرض مرورگر — Promiseمحور.
💬پیامهای پایه
توابع مرورگر مثل alert() اجرای کد را متوقف میکنند. SweetAlert2 با Promiseمحور بودن این مشکل را حل کرده و ظاهری زیبا و قابل شخصیسازی ارائه میدهد.
// سادهترین حالت Swal.fire('سلام! من یک پیام ساده هستم.'); // فرم سهپارامتری — عنوان | متن | آیکون Swal.fire('موفقیت', 'اطلاعات ذخیره شد.', 'success'); // فرم آبجکت (پیشنهادی — کنترل بیشتر) Swal.fire({ title: '<strong>پشتیبانی از HTML</strong>', html: '<b>متن بولد</b> یا <a href="#">لینک</a>', footer: '<a href="#">راهنمایی بیشتر</a>', showCloseButton: true, confirmButtonText: 'متوجه شدم!' });
| ویژگی | توضیح | مثال |
|---|---|---|
| title | عنوان اصلی | 'خوش آمدید!' |
| text | متن ساده | 'اطلاعات ذخیره شد' |
| html | محتوای HTML (جایگزین text) | '<b>مهم</b>' |
| icon | آیکون پیام | 'success' / 'error' |
| footer | متن پایین پنجره | '<a>راهنما</a>' |
| width | عرض پنجره | '400px' |
| showCloseButton | دکمه × بستن | true |
| allowOutsideClick | بستن با کلیک بیرون | false |
🎨آیکونها و انواع هشدار
SweetAlert2 دارای ۵ آیکون متحرک از پیش ساخته است که با ویژگی icon فراخوانی میشوند.
Swal.fire({ icon: 'success', title: 'عملیات موفق!' }); Swal.fire({ icon: 'error', title: 'خطا!', text: 'ارتباط برقرار نشد.', footer: '<a href="#">چرا؟</a>' }); Swal.fire({ icon: 'warning', title: 'هشدار!' }); Swal.fire({ icon: 'info', title: 'اطلاعات' }); Swal.fire({ icon: 'question',title: 'سوال' }); // سفارشیسازی رنگ آیکون Swal.fire({ icon: 'success', iconColor: '#88ce02', confirmButtonColor: '#88ce02' });
🔺دکمهها و تاییدیه
با showCancelButton دکمه انصراف نمایش داده میشود. نتیجه از طریق .then(result) دریافت میشود.
Swal.fire({ title: 'حذف فایل؟', text: 'این عملیات برگشتپذیر نیست!', icon: 'warning', showCancelButton: true, confirmButtonColor: '#d33', cancelButtonColor: '#3085d6', confirmButtonText: 'بله، حذف کن!', cancelButtonText: 'انصراف' }).then(result => { if (result.isConfirmed) Swal.fire('حذف شد!', 'فایل حذف گردید.', 'success'); else if (result.isDismissed) console.log('لغو شد — reason:', result.dismiss); }); // سه دکمه با showDenyButton Swal.fire({ title: 'تغییرات ذخیره شود؟', showDenyButton: true, showCancelButton: true, confirmButtonText: 'ذخیره', denyButtonText: 'ذخیره نکن', cancelButtonText: 'انصراف' }).then(r => { if (r.isConfirmed) Swal.fire('ذخیره شد!', '', 'success'); else if (r.isDenied) Swal.fire('ذخیره نشد', '', 'info'); });
| ویژگی | توضیح |
|---|---|
| showCancelButton | نمایش دکمه انصراف |
| showDenyButton | نمایش دکمه سوم (انکار) |
| confirmButtonText/Color | متن و رنگ دکمه تایید |
| cancelButtonText/Color | متن و رنگ دکمه انصراف |
| reverseButtons | جابجایی ترتیب دکمهها |
| result.isConfirmed | کاربر تایید کرد |
| result.isDenied | کاربر انکار کرد |
| result.isDismissed | پنجره بدون تایید بسته شد |
✍دریافت ورودی از کاربر
با تنظیم input، یک فیلد ورودی درون پنجره نمایش داده میشود. مقدار در result.value است.
// text / email / password / number / textarea / select / radio / checkbox / color / file / range Swal.fire({ title: 'ایمیل خود را وارد کنید', input: 'email', inputPlaceholder: 'user@example.com', showCancelButton: true, inputValidator: value => { if (!value) return 'ایمیل الزامی است!'; } }).then(r => { if (r.isConfirmed) Swal.fire(`ایمیل ثبت شد: ${r.value}`); });
'+r.value+'
'})})">رنگ (color)🍔Toast نوتیفیکیشن
Toastها هشدارهای کوچک غیرمزاحم هستند که در گوشههای صفحه نمایش مییابند و اجرای کد را متوقف نمیکنند.
// بهترین روش: یک mixin تعریف کنید و همه جا استفاده کنید const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, timerProgressBar: true, didOpen: toast => { toast.addEventListener('mouseenter', Swal.stopTimer); toast.addEventListener('mouseleave', Swal.resumeTimer); } }); Toast.fire({ icon: 'success', title: 'تنظیمات ذخیره شد' }); Toast.fire({ icon: 'error', title: 'خطا در اتصال!' }); Toast.fire({ icon: 'warning', title: 'حجم دیسک کم است' });
| position | موقعیت |
|---|---|
| top-end | بالا راست (پیشنهاد) |
| top | بالا مرکز |
| top-start | بالا چپ |
| bottom-end | پایین راست |
| bottom | پایین مرکز |
| center | وسط صفحه |
⏳تایمر و Progress Bar
// بسته شدن خودکار بعد از 3 ثانیه Swal.fire({ title: 'ذخیره شد!', icon: 'success', timer: 3000, // ms timerProgressBar: true, // نوار پیشرفت زیر پنجره showConfirmButton: false // بدون دکمه تایید }); // تایمر با شمارنده زنده در متن let timerInterval; Swal.fire({ title: 'در حال بسته شدن...', html: ' ثانیه دیگر', timer: 5000, timerProgressBar: true, didOpen: () => { Swal.showLoading(); timerInterval = setInterval(() => { const b = Swal.getHtmlContainer().querySelector('b'); if (b) b.textContent = Math.ceil(Swal.getTimerLeft() / 1000); }, 100); }, willClose: () => clearInterval(timerInterval) }); // کنترل تایمر از بیرون Swal.stopTimer(); // توقف Swal.resumeTimer(); // ادامه Swal.getTimerLeft(); // ms باقیمانده
🌐AJAX و Loader
با showLoaderOnConfirm و preConfirm میتوانید درخواست شبکه را مستقیم داخل SweetAlert2 مدیریت کنید.
Swal.fire({ title: 'جستجوی کاربر گیتهاب', input: 'text', inputPlaceholder: 'نام کاربری...', showCancelButton: true, confirmButtonText: 'جستجو', showLoaderOnConfirm: true, // Loader روی دکمه allowOutsideClick: () => !Swal.isLoading(), preConfirm: login => { return fetch(`https://api.github.com/users/${login}`) .then(res => { if (!res.ok) throw new Error('کاربر یافت نشد!'); return res.json(); }) .catch(err => Swal.showValidationMessage(`خطا: ${err.message}`)); } }).then(r => { if (r.isConfirmed && r.value) { Swal.fire({ title: r.value.name || r.value.login, text: `مخازن: ${r.value.public_repos}`, imageUrl: r.value.avatar_url, imageWidth: 130 }); } });
📈Wizard چند مرحلهای
با زنجیر کردن Swal.fire() یا استفاده از Swal.mixin() میتوان یک فرآیند چند مرحلهای (Wizard) ساخت:
// روش ۱: زنجیر async/await async function multiStep() { const step1 = await Swal.fire({ title: 'مرحله ۱ از ۳', input: 'text', inputPlaceholder: 'نام', showCancelButton: true, confirmButtonText: 'بعدی ←' }); if (!step1.isConfirmed) return; const step2 = await Swal.fire({ title: 'مرحله ۲ از ۳', input: 'email', inputPlaceholder: 'ایمیل', confirmButtonText: 'بعدی ←', showCancelButton: true }); if (!step2.isConfirmed) return; Swal.fire({ icon: 'success', title: 'تکمیل شد!', html: `نام: <b>${step1.value}</b><br>ایمیل: <b>${step2.value}</b>` }); } // روش ۲: Swal.mixin برای style یکنواخت const Wizard = Swal.mixin({ progressSteps: ['۱', '۲', '۳'], confirmButtonText: 'بعدی ←', showCancelButton: true });
🎨تم و استایل سفارشی
// تغییر رنگ دکمهها Swal.fire({ title: 'پیام برند', confirmButtonColor: '#88ce02', cancelButtonColor: '#e74c3c', showCancelButton: true }); // تصویر اختصاصی Swal.fire({ title: 'عکس سفارشی', imageUrl: 'https://placekitten.com/200/200', imageWidth: 200, imageAlt: 'گربه ناز' }); // customClass — تغییر کلاس CSS Swal.fire({ title: 'با CSS سفارشی', customClass: { popup: 'my-popup', title: 'my-title', confirmButton: 'my-confirm-btn', cancelButton: 'my-cancel-btn' } }); // پسزمینه سفارشی Swal.fire({ title: 'تم تاریک', background: '#1a1a2e', color: '#e0e0e0', confirmButtonColor: '#88ce02' });
🔥mixin و چیتشیت
تنظیمات سراسری با mixin
// یک بار در ابتدای پروژه تعریف کنید const MySwal = Swal.mixin({ confirmButtonColor: '#88ce02', cancelButtonColor: '#e74c3c', customClass: { confirmButton: 'my-confirm-btn', popup: 'my-popup' } }); const Toast = Swal.mixin({ toast: true, position: 'top-end', showConfirmButton: false, timer: 3000, timerProgressBar: true, didOpen: t => { t.addEventListener('mouseenter', Swal.stopTimer); t.addEventListener('mouseleave', Swal.resumeTimer); } }); // بعداً استفاده کنید MySwal.fire('موفقیت!', 'محصول اضافه شد.', 'success'); Toast.fire({ icon: 'success', title: 'ذخیره شد' }); // async/await const result = await Swal.fire({ title: '...', showCancelButton: true }); if (result.isConfirmed) { /* ... */ } // متدهای ایستا Swal.isVisible(); // آیا پنجرهای باز است؟ Swal.close(); // بستن پنجره فعلی Swal.showLoading(); // نمایش Loader روی دکمه Swal.hideLoading(); // مخفی کردن Loader Swal.getTimerLeft(); // ms باقیمانده تایمر Swal.showValidationMessage('خطا!'); // نمایش خطا در input
📄 چیتشیت سریع
| عملیات | کد سریع |
|---|---|
| پیام ساده | Swal.fire('متن') |
| موفقیت | Swal.fire('','متن','success') |
| خطا | Swal.fire({icon:'error',title:'خطا!'}) |
| تاییدیه حذف | Swal.fire({showCancelButton:true}).then(r=>r.isConfirmed&&...) |
| Toast | Swal.mixin({toast:true,position:'top-end',...}).fire(...) |
| ورودی | Swal.fire({input:'text',...}).then(r=>r.value) |
| AJAX | Swal.fire({showLoaderOnConfirm:true,preConfirm:()=>fetch(...)}) |
| تایمر خودکار | Swal.fire({timer:3000,timerProgressBar:true,showConfirmButton:false}) |
| Loader | Swal.fire({didOpen:()=>Swal.showLoading()}) |
| بستن | Swal.close() |
Toast mixin و یک MySwal mixin در فایل اصلی JS تعریف کنید. این کار ظاهر هشدارها را کاملاً یکدست نگه میدارد و کد تکراری را حذف میکند.
async/await پشتیبانی میکند: const result = await Swal.fire({...})
🚀زمین بازی کد (Playground)
انواع پیامهای SweetAlert2 را امتحان کن: پایه، آیکون، تاییدیه، ورودی کاربر و Toast. دکمهها را بزن و نتیجه را در پنل کنسول ببین. نسخهٔ ۱۱.۱۰.۷ آفلاین بارگذاری میشود.