toast.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228
  1. (function (root, factory) {
  2. if(typeof define === 'function' && define.amd) {
  3. define([], factory(root));
  4. } else if(typeof exports === 'object') {
  5. module.exports = factory(root);
  6. } else if (window.layui && layui.define) {
  7. layui.define(function(exports){
  8. exports('toast',factory(root))
  9. })
  10. }else {
  11. root.iziToast = factory(root);
  12. }
  13. })(typeof global !== 'undefined' ? global : window || this.window || this.global, function (root) {
  14. 'use strict';
  15. //
  16. // Variables
  17. //
  18. var $iziToast = {},
  19. PLUGIN_NAME = 'iziToast',
  20. BODY = document.querySelector('body'),
  21. ISMOBILE = (/Mobi/.test(navigator.userAgent)) ? true : false,
  22. ISCHROME = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor),
  23. ISFIREFOX = typeof InstallTrigger !== 'undefined',
  24. ACCEPTSTOUCH = 'ontouchstart' in document.documentElement,
  25. POSITIONS = ['bottomRight','bottomLeft','bottomCenter','topRight','topLeft','topCenter','center'],
  26. THEMES = {
  27. info: {
  28. color: 'blue',
  29. icon: 'ico-info'
  30. },
  31. success: {
  32. color: 'green',
  33. icon: 'ico-success'
  34. },
  35. warning: {
  36. color: 'orange',
  37. icon: 'ico-warning'
  38. },
  39. error: {
  40. color: 'red',
  41. icon: 'ico-error'
  42. },
  43. question: {
  44. color: 'yellow',
  45. icon: 'ico-question'
  46. }
  47. },
  48. MOBILEWIDTH = 568,
  49. CONFIG = {};
  50. $iziToast.children = {};
  51. // Default settings
  52. var defaults = {
  53. id: null,
  54. class: '',
  55. title: '',
  56. titleColor: '',
  57. titleSize: '',
  58. titleLineHeight: '',
  59. message: '',
  60. messageColor: '',
  61. messageSize: '',
  62. messageLineHeight: '',
  63. backgroundColor: '',
  64. theme: 'light', // dark
  65. color: '', // blue, red, green, yellow
  66. icon: '',
  67. iconText: '',
  68. iconColor: '',
  69. iconUrl: null,
  70. image: '',
  71. imageWidth: 50,
  72. maxWidth: null,
  73. zindex: null,
  74. layout: 2,
  75. balloon: false,
  76. close: true,
  77. closeOnEscape: false,
  78. closeOnClick: false,
  79. displayMode: 0,
  80. position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter, center
  81. target: '',
  82. targetFirst: true,
  83. timeout: 3000, // 默认3秒
  84. rtl: false,
  85. animateInside: false, // 动画效果
  86. drag: true,
  87. pauseOnHover: true,
  88. resetOnHover: false,
  89. progressBar: false,
  90. progressBarColor: '',
  91. progressBarEasing: 'linear',
  92. overlay: false,
  93. overlayClose: false,
  94. overlayColor: 'rgba(0, 0, 0, 0.6)',
  95. transitionIn: 'fadeInDown', // bounceInLeft, bounceInRight, bounceInUp, bounceInDown, fadeIn, fadeInDown, fadeInUp, fadeInLeft, fadeInRight, flipInX
  96. transitionOut: 'fadeOut', // fadeOut, fadeOutUp, fadeOutDown, fadeOutLeft, fadeOutRight, flipOutX
  97. transitionInMobile: 'bounceInDown',
  98. transitionOutMobile: 'fadeOutUp',
  99. buttons: {},
  100. inputs: {},
  101. onOpening: function () {},
  102. onOpened: function () {},
  103. onClosing: function () {},
  104. onClosed: function () {}
  105. };
  106. if(!('remove' in Element.prototype)) {
  107. Element.prototype.remove = function() {
  108. if(this.parentNode) {
  109. this.parentNode.removeChild(this);
  110. }
  111. };
  112. }
  113. if(typeof window.CustomEvent !== 'function') {
  114. var CustomEventPolyfill = function (event, params) {
  115. params = params || { bubbles: false, cancelable: false, detail: undefined };
  116. var evt = document.createEvent('CustomEvent');
  117. evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
  118. return evt;
  119. };
  120. CustomEventPolyfill.prototype = window.Event.prototype;
  121. window.CustomEvent = CustomEventPolyfill;
  122. }
  123. var forEach = function (collection, callback, scope) {
  124. if(Object.prototype.toString.call(collection) === '[object Object]') {
  125. for (var prop in collection) {
  126. if(Object.prototype.hasOwnProperty.call(collection, prop)) {
  127. callback.call(scope, collection[prop], prop, collection);
  128. }
  129. }
  130. } else {
  131. if(collection){
  132. for (var i = 0, len = collection.length; i < len; i++) {
  133. callback.call(scope, collection[i], i, collection);
  134. }
  135. }
  136. }
  137. };
  138. var extend = function (defaults, options) {
  139. var extended = {};
  140. forEach(defaults, function (value, prop) {
  141. extended[prop] = defaults[prop];
  142. });
  143. forEach(options, function (value, prop) {
  144. extended[prop] = options[prop];
  145. });
  146. return extended;
  147. };
  148. var createFragElem = function(htmlStr) {
  149. var frag = document.createDocumentFragment(),
  150. temp = document.createElement('div');
  151. temp.innerHTML = htmlStr;
  152. while (temp.firstChild) {
  153. frag.appendChild(temp.firstChild);
  154. }
  155. return frag;
  156. };
  157. var generateId = function(params) {
  158. var newId = btoa(encodeURIComponent(params));
  159. return newId.replace(/=/g, "");
  160. };
  161. var isColor = function(color){
  162. if( color.substring(0,1) == '#' || color.substring(0,3) == 'rgb' || color.substring(0,3) == 'hsl' ){
  163. return true;
  164. } else {
  165. return false;
  166. }
  167. };
  168. var isBase64 = function(str) {
  169. try {
  170. return btoa(atob(str)) == str;
  171. } catch (err) {
  172. return false;
  173. }
  174. };
  175. var drag = function() {
  176. return {
  177. move: function(toast, instance, settings, xpos) {
  178. var opacity,
  179. opacityRange = 0.3,
  180. distance = 180;
  181. if(xpos !== 0){
  182. toast.classList.add(PLUGIN_NAME+'-dragged');
  183. toast.style.transform = 'translateX('+xpos + 'px)';
  184. if(xpos > 0){
  185. opacity = (distance-xpos) / distance;
  186. if(opacity < opacityRange){
  187. instance.hide(extend(settings, { transitionOut: 'fadeOutRight', transitionOutMobile: 'fadeOutRight' }), toast, 'drag');
  188. }
  189. } else {
  190. opacity = (distance+xpos) / distance;
  191. if(opacity < opacityRange){
  192. instance.hide(extend(settings, { transitionOut: 'fadeOutLeft', transitionOutMobile: 'fadeOutLeft' }), toast, 'drag');
  193. }
  194. }
  195. toast.style.opacity = opacity;
  196. if(opacity < opacityRange){
  197. if(ISCHROME || ISFIREFOX)
  198. toast.style.left = xpos+'px';
  199. toast.parentNode.style.opacity = opacityRange;
  200. this.stopMoving(toast, null);
  201. }
  202. }
  203. },
  204. startMoving: function(toast, instance, settings, e) {
  205. e = e || window.event;
  206. var posX = ((ACCEPTSTOUCH) ? e.touches[0].clientX : e.clientX),
  207. toastLeft = toast.style.transform.replace('px)', '');
  208. toastLeft = toastLeft.replace('translateX(', '');
  209. var offsetX = posX - toastLeft;
  210. if(settings.transitionIn){
  211. toast.classList.remove(settings.transitionIn);
  212. }
  213. if(settings.transitionInMobile){
  214. toast.classList.remove(settings.transitionInMobile);
  215. }
  216. toast.style.transition = '';
  217. if(ACCEPTSTOUCH) {
  218. document.ontouchmove = function(e) {
  219. e.preventDefault();
  220. e = e || window.event;
  221. var posX = e.touches[0].clientX,
  222. finalX = posX - offsetX;
  223. drag.move(toast, instance, settings, finalX);
  224. };
  225. } else {
  226. document.onmousemove = function(e) {
  227. e.preventDefault();
  228. e = e || window.event;
  229. var posX = e.clientX,
  230. finalX = posX - offsetX;
  231. drag.move(toast, instance, settings, finalX);
  232. };
  233. }
  234. },
  235. stopMoving: function(toast, e) {
  236. if(ACCEPTSTOUCH) {
  237. document.ontouchmove = function() {};
  238. } else {
  239. document.onmousemove = function() {};
  240. }
  241. toast.style.opacity = '';
  242. toast.style.transform = '';
  243. if(toast.classList.contains(PLUGIN_NAME+'-dragged')){
  244. toast.classList.remove(PLUGIN_NAME+'-dragged');
  245. toast.style.transition = 'transform 0.4s ease, opacity 0.4s ease';
  246. setTimeout(function() {
  247. toast.style.transition = '';
  248. }, 400);
  249. }
  250. }
  251. };
  252. }();
  253. $iziToast.setSetting = function (ref, option, value) {
  254. $iziToast.children[ref][option] = value;
  255. };
  256. $iziToast.getSetting = function (ref, option) {
  257. return $iziToast.children[ref][option];
  258. };
  259. $iziToast.destroy = function () {
  260. forEach(document.querySelectorAll('.'+PLUGIN_NAME+'-overlay'), function(element, index) {
  261. element.remove();
  262. });
  263. forEach(document.querySelectorAll('.'+PLUGIN_NAME+'-wrapper'), function(element, index) {
  264. element.remove();
  265. });
  266. forEach(document.querySelectorAll('.'+PLUGIN_NAME), function(element, index) {
  267. element.remove();
  268. });
  269. this.children = {};
  270. // Remove event listeners
  271. document.removeEventListener(PLUGIN_NAME+'-opened', {}, false);
  272. document.removeEventListener(PLUGIN_NAME+'-opening', {}, false);
  273. document.removeEventListener(PLUGIN_NAME+'-closing', {}, false);
  274. document.removeEventListener(PLUGIN_NAME+'-closed', {}, false);
  275. document.removeEventListener('keyup', {}, false);
  276. // Reset variables
  277. CONFIG = {};
  278. };
  279. /**
  280. * Initialize Plugin
  281. * @public
  282. * @param {Object} options User settings
  283. */
  284. $iziToast.settings = function (options) {
  285. // Destroy any existing initializations
  286. $iziToast.destroy();
  287. CONFIG = options;
  288. defaults = extend(defaults, options || {});
  289. };
  290. /**
  291. * Building themes functions.
  292. * @public
  293. * @param {Object} options User settings
  294. */
  295. forEach(THEMES, function (theme, name) {
  296. $iziToast[name] = function (options) {
  297. var settings = extend(CONFIG, options || {});
  298. settings = extend(theme, settings || {});
  299. this.show(settings);
  300. };
  301. });
  302. /**
  303. * Do the calculation to move the progress bar
  304. * @private
  305. */
  306. $iziToast.progress = function (options, $toast, callback) {
  307. var that = this,
  308. ref = $toast.getAttribute('data-iziToast-ref'),
  309. settings = extend(this.children[ref], options || {}),
  310. $elem = $toast.querySelector('.'+PLUGIN_NAME+'-progressbar div');
  311. return {
  312. start: function() {
  313. if(typeof settings.time.REMAINING == 'undefined'){
  314. $toast.classList.remove(PLUGIN_NAME+'-reseted');
  315. if($elem !== null){
  316. $elem.style.transition = 'width '+ settings.timeout +'ms '+settings.progressBarEasing;
  317. $elem.style.width = '0%';
  318. }
  319. settings.time.START = new Date().getTime();
  320. settings.time.END = settings.time.START + settings.timeout;
  321. settings.time.TIMER = setTimeout(function() {
  322. clearTimeout(settings.time.TIMER);
  323. if(!$toast.classList.contains(PLUGIN_NAME+'-closing')){
  324. that.hide(settings, $toast, 'timeout');
  325. if(typeof callback === 'function'){
  326. callback.apply(that);
  327. }
  328. }
  329. }, settings.timeout);
  330. that.setSetting(ref, 'time', settings.time);
  331. }
  332. },
  333. pause: function() {
  334. if(typeof settings.time.START !== 'undefined' && !$toast.classList.contains(PLUGIN_NAME+'-paused') && !$toast.classList.contains(PLUGIN_NAME+'-reseted')){
  335. $toast.classList.add(PLUGIN_NAME+'-paused');
  336. settings.time.REMAINING = settings.time.END - new Date().getTime();
  337. clearTimeout(settings.time.TIMER);
  338. that.setSetting(ref, 'time', settings.time);
  339. if($elem !== null){
  340. var computedStyle = window.getComputedStyle($elem),
  341. propertyWidth = computedStyle.getPropertyValue('width');
  342. $elem.style.transition = 'none';
  343. $elem.style.width = propertyWidth;
  344. }
  345. if(typeof callback === 'function'){
  346. setTimeout(function() {
  347. callback.apply(that);
  348. }, 10);
  349. }
  350. }
  351. },
  352. resume: function() {
  353. if(typeof settings.time.REMAINING !== 'undefined'){
  354. $toast.classList.remove(PLUGIN_NAME+'-paused');
  355. if($elem !== null){
  356. $elem.style.transition = 'width '+ settings.time.REMAINING +'ms '+settings.progressBarEasing;
  357. $elem.style.width = '0%';
  358. }
  359. settings.time.END = new Date().getTime() + settings.time.REMAINING;
  360. settings.time.TIMER = setTimeout(function() {
  361. clearTimeout(settings.time.TIMER);
  362. if(!$toast.classList.contains(PLUGIN_NAME+'-closing')){
  363. that.hide(settings, $toast, 'timeout');
  364. if(typeof callback === 'function'){
  365. callback.apply(that);
  366. }
  367. }
  368. }, settings.time.REMAINING);
  369. that.setSetting(ref, 'time', settings.time);
  370. } else {
  371. this.start();
  372. }
  373. },
  374. reset: function(){
  375. clearTimeout(settings.time.TIMER);
  376. delete settings.time.REMAINING;
  377. that.setSetting(ref, 'time', settings.time);
  378. $toast.classList.add(PLUGIN_NAME+'-reseted');
  379. $toast.classList.remove(PLUGIN_NAME+'-paused');
  380. if($elem !== null){
  381. $elem.style.transition = 'none';
  382. $elem.style.width = '100%';
  383. }
  384. if(typeof callback === 'function'){
  385. setTimeout(function() {
  386. callback.apply(that);
  387. }, 10);
  388. }
  389. }
  390. };
  391. };
  392. /**
  393. * Close the specific Toast
  394. * @public
  395. * @param {Object} options User settings
  396. */
  397. $iziToast.hide = function (options, $toast, closedBy) {
  398. if(typeof $toast != 'object'){
  399. $toast = document.querySelector($toast);
  400. }
  401. var that = this,
  402. settings = extend(this.children[$toast.getAttribute('data-iziToast-ref')], options || {});
  403. settings.closedBy = closedBy || null;
  404. delete settings.time.REMAINING;
  405. $toast.classList.add(PLUGIN_NAME+'-closing');
  406. // Overlay
  407. (function(){
  408. var $overlay = document.querySelector('.'+PLUGIN_NAME+'-overlay');
  409. if($overlay !== null){
  410. var refs = $overlay.getAttribute('data-iziToast-ref');
  411. refs = refs.split(',');
  412. var index = refs.indexOf(String(settings.ref));
  413. if(index !== -1){
  414. refs.splice(index, 1);
  415. }
  416. $overlay.setAttribute('data-iziToast-ref', refs.join());
  417. if(refs.length === 0){
  418. $overlay.classList.remove('fadeIn');
  419. $overlay.classList.add('fadeOut');
  420. setTimeout(function() {
  421. $overlay.remove();
  422. }, 700);
  423. }
  424. }
  425. })();
  426. if(settings.transitionIn){
  427. $toast.classList.remove(settings.transitionIn);
  428. }
  429. if(settings.transitionInMobile){
  430. $toast.classList.remove(settings.transitionInMobile);
  431. }
  432. if(ISMOBILE || window.innerWidth <= MOBILEWIDTH){
  433. if(settings.transitionOutMobile)
  434. $toast.classList.add(settings.transitionOutMobile);
  435. } else {
  436. if(settings.transitionOut)
  437. $toast.classList.add(settings.transitionOut);
  438. }
  439. var H = $toast.parentNode.offsetHeight;
  440. $toast.parentNode.style.height = H+'px';
  441. $toast.style.pointerEvents = 'none';
  442. if(!ISMOBILE || window.innerWidth > MOBILEWIDTH){
  443. $toast.parentNode.style.transitionDelay = '0.2s';
  444. }
  445. try {
  446. var event = new CustomEvent(PLUGIN_NAME+'-closing', {detail: settings, bubbles: true, cancelable: true});
  447. document.dispatchEvent(event);
  448. } catch(ex){
  449. console.warn(ex);
  450. }
  451. setTimeout(function() {
  452. $toast.parentNode.style.height = '0px';
  453. $toast.parentNode.style.overflow = '';
  454. setTimeout(function(){
  455. delete that.children[settings.ref];
  456. $toast.parentNode.remove();
  457. try {
  458. var event = new CustomEvent(PLUGIN_NAME+'-closed', {detail: settings, bubbles: true, cancelable: true});
  459. document.dispatchEvent(event);
  460. } catch(ex){
  461. console.warn(ex);
  462. }
  463. if(typeof settings.onClosed !== 'undefined'){
  464. settings.onClosed.apply(null, [settings, $toast, closedBy]);
  465. }
  466. }, 1000);
  467. }, 200);
  468. if(typeof settings.onClosing !== 'undefined'){
  469. settings.onClosing.apply(null, [settings, $toast, closedBy]);
  470. }
  471. };
  472. /**
  473. * Create and show the Toast
  474. * @public
  475. * @param {Object} options User settings
  476. */
  477. $iziToast.show = function (options) {
  478. var that = this;
  479. // Merge user options with defaults
  480. var settings = extend(CONFIG, options || {});
  481. settings = extend(defaults, settings);
  482. settings.time = {};
  483. if(settings.id === null){
  484. settings.id = generateId(settings.title+settings.message+settings.color);
  485. }
  486. if(settings.displayMode === 1 || settings.displayMode == 'once'){
  487. try {
  488. if(document.querySelectorAll('.'+PLUGIN_NAME+'#'+settings.id).length > 0){
  489. return false;
  490. }
  491. } catch (exc) {
  492. console.warn('['+PLUGIN_NAME+'] Could not find an element with this selector: '+'#'+settings.id+'. Try to set an valid id.');
  493. }
  494. }
  495. if(settings.displayMode === 2 || settings.displayMode == 'replace'){
  496. try {
  497. forEach(document.querySelectorAll('.'+PLUGIN_NAME+'#'+settings.id), function(element, index) {
  498. that.hide(settings, element, 'replaced');
  499. });
  500. } catch (exc) {
  501. console.warn('['+PLUGIN_NAME+'] Could not find an element with this selector: '+'#'+settings.id+'. Try to set an valid id.');
  502. }
  503. }
  504. settings.ref = new Date().getTime() + Math.floor((Math.random() * 10000000) + 1);
  505. $iziToast.children[settings.ref] = settings;
  506. var $DOM = {
  507. body: document.querySelector('body'),
  508. overlay: document.createElement('div'),
  509. toast: document.createElement('div'),
  510. toastBody: document.createElement('div'),
  511. toastTexts: document.createElement('div'),
  512. toastCapsule: document.createElement('div'),
  513. cover: document.createElement('div'),
  514. buttons: document.createElement('div'),
  515. inputs: document.createElement('div'),
  516. icon: !settings.iconUrl ? document.createElement('i') : document.createElement('img'),
  517. wrapper: null
  518. };
  519. $DOM.toast.setAttribute('data-iziToast-ref', settings.ref);
  520. $DOM.toast.appendChild($DOM.toastBody);
  521. $DOM.toastCapsule.appendChild($DOM.toast);
  522. // CSS Settings
  523. (function(){
  524. $DOM.toast.classList.add(PLUGIN_NAME);
  525. $DOM.toast.classList.add(PLUGIN_NAME+'-opening');
  526. $DOM.toastCapsule.classList.add(PLUGIN_NAME+'-capsule');
  527. $DOM.toastBody.classList.add(PLUGIN_NAME + '-body');
  528. $DOM.toastTexts.classList.add(PLUGIN_NAME + '-texts');
  529. if(ISMOBILE || window.innerWidth <= MOBILEWIDTH){
  530. if(settings.transitionInMobile)
  531. $DOM.toast.classList.add(settings.transitionInMobile);
  532. } else {
  533. if(settings.transitionIn)
  534. $DOM.toast.classList.add(settings.transitionIn);
  535. }
  536. if(settings.class){
  537. var classes = settings.class.split(' ');
  538. forEach(classes, function (value, index) {
  539. $DOM.toast.classList.add(value);
  540. });
  541. }
  542. if(settings.id){ $DOM.toast.id = settings.id; }
  543. if(settings.rtl){
  544. $DOM.toast.classList.add(PLUGIN_NAME + '-rtl');
  545. $DOM.toast.setAttribute('dir', 'rtl');
  546. }
  547. if(settings.layout > 1){ $DOM.toast.classList.add(PLUGIN_NAME+'-layout'+settings.layout); }
  548. if(settings.balloon){ $DOM.toast.classList.add(PLUGIN_NAME+'-balloon'); }
  549. if(settings.maxWidth){
  550. if( !isNaN(settings.maxWidth) ){
  551. $DOM.toast.style.maxWidth = settings.maxWidth+'px';
  552. } else {
  553. $DOM.toast.style.maxWidth = settings.maxWidth;
  554. }
  555. }
  556. if(settings.theme !== '' || settings.theme !== 'light') {
  557. $DOM.toast.classList.add(PLUGIN_NAME+'-theme-'+settings.theme);
  558. }
  559. if(settings.color) { //#, rgb, rgba, hsl
  560. if( isColor(settings.color) ){
  561. $DOM.toast.style.background = settings.color;
  562. } else {
  563. $DOM.toast.classList.add(PLUGIN_NAME+'-color-'+settings.color);
  564. }
  565. }
  566. if(settings.backgroundColor) {
  567. $DOM.toast.style.background = settings.backgroundColor;
  568. if(settings.balloon){
  569. $DOM.toast.style.borderColor = settings.backgroundColor;
  570. }
  571. }
  572. })();
  573. // Cover image
  574. (function(){
  575. if(settings.image) {
  576. $DOM.cover.classList.add(PLUGIN_NAME + '-cover');
  577. $DOM.cover.style.width = settings.imageWidth + 'px';
  578. if(isBase64(settings.image.replace(/ /g,''))){
  579. $DOM.cover.style.backgroundImage = 'url(data:image/png;base64,' + settings.image.replace(/ /g,'') + ')';
  580. } else {
  581. $DOM.cover.style.backgroundImage = 'url(' + settings.image + ')';
  582. }
  583. if(settings.rtl){
  584. $DOM.toastBody.style.marginRight = (settings.imageWidth + 10) + 'px';
  585. } else {
  586. $DOM.toastBody.style.marginLeft = (settings.imageWidth + 10) + 'px';
  587. }
  588. $DOM.toast.appendChild($DOM.cover);
  589. }
  590. })();
  591. // Button close
  592. (function(){
  593. if(settings.close){
  594. $DOM.buttonClose = document.createElement('button');
  595. $DOM.buttonClose.type = 'button';
  596. $DOM.buttonClose.classList.add(PLUGIN_NAME + '-close');
  597. $DOM.buttonClose.addEventListener('click', function (e) {
  598. var button = e.target;
  599. that.hide(settings, $DOM.toast, 'button');
  600. });
  601. $DOM.toast.appendChild($DOM.buttonClose);
  602. } else {
  603. if(settings.rtl){
  604. $DOM.toast.style.paddingLeft = '18px';
  605. } else {
  606. $DOM.toast.style.paddingRight = '18px';
  607. }
  608. }
  609. })();
  610. // Progress Bar & Timeout
  611. (function(){
  612. if(settings.progressBar){
  613. $DOM.progressBar = document.createElement('div');
  614. $DOM.progressBarDiv = document.createElement('div');
  615. $DOM.progressBar.classList.add(PLUGIN_NAME + '-progressbar');
  616. $DOM.progressBarDiv.style.background = settings.progressBarColor;
  617. $DOM.progressBar.appendChild($DOM.progressBarDiv);
  618. $DOM.toast.appendChild($DOM.progressBar);
  619. }
  620. if(settings.timeout) {
  621. if(settings.pauseOnHover && !settings.resetOnHover){
  622. $DOM.toast.addEventListener('mouseenter', function (e) {
  623. that.progress(settings, $DOM.toast).pause();
  624. });
  625. $DOM.toast.addEventListener('mouseleave', function (e) {
  626. that.progress(settings, $DOM.toast).resume();
  627. });
  628. }
  629. if(settings.resetOnHover){
  630. $DOM.toast.addEventListener('mouseenter', function (e) {
  631. that.progress(settings, $DOM.toast).reset();
  632. });
  633. $DOM.toast.addEventListener('mouseleave', function (e) {
  634. that.progress(settings, $DOM.toast).start();
  635. });
  636. }
  637. }
  638. })();
  639. // Icon
  640. (function(){
  641. if(settings.iconUrl) {
  642. $DOM.icon.setAttribute('class', PLUGIN_NAME + '-icon');
  643. $DOM.icon.setAttribute('src', settings.iconUrl);
  644. } else if(settings.icon) {
  645. $DOM.icon.setAttribute('class', PLUGIN_NAME + '-icon ' + settings.icon);
  646. if(settings.iconText){
  647. $DOM.icon.appendChild(document.createTextNode(settings.iconText));
  648. }
  649. if(settings.iconColor){
  650. $DOM.icon.style.color = settings.iconColor;
  651. }
  652. }
  653. if(settings.icon || settings.iconUrl) {
  654. if(settings.rtl){
  655. $DOM.toastBody.style.paddingRight = '33px';
  656. } else {
  657. $DOM.toastBody.style.paddingLeft = '33px';
  658. }
  659. $DOM.toastBody.appendChild($DOM.icon);
  660. }
  661. })();
  662. // Title & Message
  663. (function(){
  664. if(settings.title.length > 0) {
  665. $DOM.strong = document.createElement('strong');
  666. $DOM.strong.classList.add(PLUGIN_NAME + '-title');
  667. $DOM.strong.appendChild(createFragElem(settings.title));
  668. $DOM.toastTexts.appendChild($DOM.strong);
  669. if(settings.titleColor) {
  670. $DOM.strong.style.color = settings.titleColor;
  671. }
  672. if(settings.titleSize) {
  673. if( !isNaN(settings.titleSize) ){
  674. $DOM.strong.style.fontSize = settings.titleSize+'px';
  675. } else {
  676. $DOM.strong.style.fontSize = settings.titleSize;
  677. }
  678. }
  679. if(settings.titleLineHeight) {
  680. if( !isNaN(settings.titleSize) ){
  681. $DOM.strong.style.lineHeight = settings.titleLineHeight+'px';
  682. } else {
  683. $DOM.strong.style.lineHeight = settings.titleLineHeight;
  684. }
  685. }
  686. }
  687. if(settings.message.length > 0) {
  688. $DOM.p = document.createElement('p');
  689. $DOM.p.classList.add(PLUGIN_NAME + '-message');
  690. $DOM.p.appendChild(createFragElem(settings.message));
  691. $DOM.toastTexts.appendChild($DOM.p);
  692. if(settings.messageColor) {
  693. $DOM.p.style.color = settings.messageColor;
  694. }
  695. if(settings.messageSize) {
  696. if( !isNaN(settings.titleSize) ){
  697. $DOM.p.style.fontSize = settings.messageSize+'px';
  698. } else {
  699. $DOM.p.style.fontSize = settings.messageSize;
  700. }
  701. }
  702. if(settings.messageLineHeight) {
  703. if( !isNaN(settings.titleSize) ){
  704. $DOM.p.style.lineHeight = settings.messageLineHeight+'px';
  705. } else {
  706. $DOM.p.style.lineHeight = settings.messageLineHeight;
  707. }
  708. }
  709. }
  710. if(settings.title.length > 0 && settings.message.length > 0) {
  711. if(settings.rtl){
  712. $DOM.strong.style.marginLeft = '10px';
  713. } else if(settings.layout !== 2 && !settings.rtl) {
  714. $DOM.strong.style.marginRight = '10px';
  715. }
  716. }
  717. })();
  718. $DOM.toastBody.appendChild($DOM.toastTexts);
  719. // Inputs
  720. var $inputs;
  721. (function(){
  722. if(settings.inputs.length > 0) {
  723. $DOM.inputs.classList.add(PLUGIN_NAME + '-inputs');
  724. forEach(settings.inputs, function (value, index) {
  725. $DOM.inputs.appendChild(createFragElem(value[0]));
  726. $inputs = $DOM.inputs.childNodes;
  727. $inputs[index].classList.add(PLUGIN_NAME + '-inputs-child');
  728. if(value[3]){
  729. setTimeout(function() {
  730. $inputs[index].focus();
  731. }, 300);
  732. }
  733. $inputs[index].addEventListener(value[1], function (e) {
  734. var ts = value[2];
  735. return ts(that, $DOM.toast, this, e);
  736. });
  737. });
  738. $DOM.toastBody.appendChild($DOM.inputs);
  739. }
  740. })();
  741. // Buttons
  742. (function(){
  743. if(settings.buttons.length > 0) {
  744. $DOM.buttons.classList.add(PLUGIN_NAME + '-buttons');
  745. forEach(settings.buttons, function (value, index) {
  746. $DOM.buttons.appendChild(createFragElem(value[0]));
  747. var $btns = $DOM.buttons.childNodes;
  748. $btns[index].classList.add(PLUGIN_NAME + '-buttons-child');
  749. if(value[2]){
  750. setTimeout(function() {
  751. $btns[index].focus();
  752. }, 300);
  753. }
  754. $btns[index].addEventListener('click', function (e) {
  755. e.preventDefault();
  756. var ts = value[1];
  757. return ts(that, $DOM.toast, this, e, $inputs);
  758. });
  759. });
  760. }
  761. $DOM.toastBody.appendChild($DOM.buttons);
  762. })();
  763. if(settings.message.length > 0 && (settings.inputs.length > 0 || settings.buttons.length > 0)) {
  764. $DOM.p.style.marginBottom = '0';
  765. }
  766. if(settings.inputs.length > 0 || settings.buttons.length > 0){
  767. if(settings.rtl){
  768. $DOM.toastTexts.style.marginLeft = '10px';
  769. } else {
  770. $DOM.toastTexts.style.marginRight = '10px';
  771. }
  772. if(settings.inputs.length > 0 && settings.buttons.length > 0){
  773. if(settings.rtl){
  774. $DOM.inputs.style.marginLeft = '8px';
  775. } else {
  776. $DOM.inputs.style.marginRight = '8px';
  777. }
  778. }
  779. }
  780. // Wrap
  781. (function(){
  782. $DOM.toastCapsule.style.visibility = 'hidden';
  783. setTimeout(function() {
  784. var H = $DOM.toast.offsetHeight;
  785. var style = $DOM.toast.currentStyle || window.getComputedStyle($DOM.toast);
  786. var marginTop = style.marginTop;
  787. marginTop = marginTop.split('px');
  788. marginTop = parseInt(marginTop[0]);
  789. var marginBottom = style.marginBottom;
  790. marginBottom = marginBottom.split('px');
  791. marginBottom = parseInt(marginBottom[0]);
  792. $DOM.toastCapsule.style.visibility = '';
  793. $DOM.toastCapsule.style.height = (H+marginBottom+marginTop)+'px';
  794. setTimeout(function() {
  795. $DOM.toastCapsule.style.height = 'auto';
  796. if(settings.target){
  797. $DOM.toastCapsule.style.overflow = 'visible';
  798. }
  799. }, 500);
  800. if(settings.timeout) {
  801. that.progress(settings, $DOM.toast).start();
  802. }
  803. }, 100);
  804. })();
  805. // Target
  806. (function(){
  807. var position = settings.position;
  808. if(settings.target){
  809. $DOM.wrapper = document.querySelector(settings.target);
  810. $DOM.wrapper.classList.add(PLUGIN_NAME + '-target');
  811. if(settings.targetFirst) {
  812. $DOM.wrapper.insertBefore($DOM.toastCapsule, $DOM.wrapper.firstChild);
  813. } else {
  814. $DOM.wrapper.appendChild($DOM.toastCapsule);
  815. }
  816. } else {
  817. if( POSITIONS.indexOf(settings.position) == -1 ){
  818. console.warn('['+PLUGIN_NAME+'] Incorrect position.\nIt can be › ' + POSITIONS);
  819. return;
  820. }
  821. if(ISMOBILE || window.innerWidth <= MOBILEWIDTH){
  822. if(settings.position == 'bottomLeft' || settings.position == 'bottomRight' || settings.position == 'bottomCenter'){
  823. position = PLUGIN_NAME+'-wrapper-bottomCenter';
  824. }
  825. else if(settings.position == 'topLeft' || settings.position == 'topRight' || settings.position == 'topCenter'){
  826. position = PLUGIN_NAME+'-wrapper-topCenter';
  827. }
  828. else {
  829. position = PLUGIN_NAME+'-wrapper-center';
  830. }
  831. } else {
  832. position = PLUGIN_NAME+'-wrapper-'+position;
  833. }
  834. $DOM.wrapper = document.querySelector('.' + PLUGIN_NAME + '-wrapper.'+position);
  835. if(!$DOM.wrapper) {
  836. $DOM.wrapper = document.createElement('div');
  837. $DOM.wrapper.classList.add(PLUGIN_NAME + '-wrapper');
  838. $DOM.wrapper.classList.add(position);
  839. document.body.appendChild($DOM.wrapper);
  840. }
  841. if(settings.position == 'topLeft' || settings.position == 'topCenter' || settings.position == 'topRight'){
  842. $DOM.wrapper.insertBefore($DOM.toastCapsule, $DOM.wrapper.firstChild);
  843. } else {
  844. $DOM.wrapper.appendChild($DOM.toastCapsule);
  845. }
  846. }
  847. if(!isNaN(settings.zindex)) {
  848. $DOM.wrapper.style.zIndex = settings.zindex;
  849. } else {
  850. console.warn('['+PLUGIN_NAME+'] Invalid zIndex.');
  851. }
  852. })();
  853. // Overlay
  854. (function(){
  855. if(settings.overlay) {
  856. if( document.querySelector('.'+PLUGIN_NAME+'-overlay.fadeIn') !== null ){
  857. $DOM.overlay = document.querySelector('.'+PLUGIN_NAME+'-overlay');
  858. $DOM.overlay.setAttribute('data-iziToast-ref', $DOM.overlay.getAttribute('data-iziToast-ref') + ',' + settings.ref);
  859. if(!isNaN(settings.zindex) && settings.zindex !== null) {
  860. $DOM.overlay.style.zIndex = settings.zindex-1;
  861. }
  862. } else {
  863. $DOM.overlay.classList.add(PLUGIN_NAME+'-overlay');
  864. $DOM.overlay.classList.add('fadeIn');
  865. $DOM.overlay.style.background = settings.overlayColor;
  866. $DOM.overlay.setAttribute('data-iziToast-ref', settings.ref);
  867. if(!isNaN(settings.zindex) && settings.zindex !== null) {
  868. $DOM.overlay.style.zIndex = settings.zindex-1;
  869. }
  870. document.querySelector('body').appendChild($DOM.overlay);
  871. }
  872. if(settings.overlayClose) {
  873. $DOM.overlay.removeEventListener('click', {});
  874. $DOM.overlay.addEventListener('click', function (e) {
  875. that.hide(settings, $DOM.toast, 'overlay');
  876. });
  877. } else {
  878. $DOM.overlay.removeEventListener('click', {});
  879. }
  880. }
  881. })();
  882. // Inside animations
  883. (function(){
  884. if(settings.animateInside){
  885. $DOM.toast.classList.add(PLUGIN_NAME+'-animateInside');
  886. var animationTimes = [200, 100, 300];
  887. if(settings.transitionIn == 'bounceInLeft' || settings.transitionIn == 'bounceInRight'){
  888. animationTimes = [400, 200, 400];
  889. }
  890. if(settings.title.length > 0) {
  891. setTimeout(function(){
  892. $DOM.strong.classList.add('slideIn');
  893. }, animationTimes[0]);
  894. }
  895. if(settings.message.length > 0) {
  896. setTimeout(function(){
  897. $DOM.p.classList.add('slideIn');
  898. }, animationTimes[1]);
  899. }
  900. if(settings.icon || settings.iconUrl) {
  901. setTimeout(function(){
  902. $DOM.icon.classList.add('revealIn');
  903. }, animationTimes[2]);
  904. }
  905. var counter = 150;
  906. if(settings.buttons.length > 0 && $DOM.buttons) {
  907. setTimeout(function(){
  908. forEach($DOM.buttons.childNodes, function(element, index) {
  909. setTimeout(function(){
  910. element.classList.add('revealIn');
  911. }, counter);
  912. counter = counter + 150;
  913. });
  914. }, settings.inputs.length > 0 ? 150 : 0);
  915. }
  916. if(settings.inputs.length > 0 && $DOM.inputs) {
  917. counter = 150;
  918. forEach($DOM.inputs.childNodes, function(element, index) {
  919. setTimeout(function(){
  920. element.classList.add('revealIn');
  921. }, counter);
  922. counter = counter + 150;
  923. });
  924. }
  925. }
  926. })();
  927. settings.onOpening.apply(null, [settings, $DOM.toast]);
  928. try {
  929. var event = new CustomEvent(PLUGIN_NAME + '-opening', {detail: settings, bubbles: true, cancelable: true});
  930. document.dispatchEvent(event);
  931. } catch(ex){
  932. console.warn(ex);
  933. }
  934. setTimeout(function() {
  935. $DOM.toast.classList.remove(PLUGIN_NAME+'-opening');
  936. $DOM.toast.classList.add(PLUGIN_NAME+'-opened');
  937. try {
  938. var event = new CustomEvent(PLUGIN_NAME + '-opened', {detail: settings, bubbles: true, cancelable: true});
  939. document.dispatchEvent(event);
  940. } catch(ex){
  941. console.warn(ex);
  942. }
  943. settings.onOpened.apply(null, [settings, $DOM.toast]);
  944. }, 1000);
  945. if(settings.drag){
  946. if(ACCEPTSTOUCH) {
  947. $DOM.toast.addEventListener('touchstart', function(e) {
  948. drag.startMoving(this, that, settings, e);
  949. }, false);
  950. $DOM.toast.addEventListener('touchend', function(e) {
  951. drag.stopMoving(this, e);
  952. }, false);
  953. } else {
  954. $DOM.toast.addEventListener('mousedown', function(e) {
  955. e.preventDefault();
  956. drag.startMoving(this, that, settings, e);
  957. }, false);
  958. $DOM.toast.addEventListener('mouseup', function(e) {
  959. e.preventDefault();
  960. drag.stopMoving(this, e);
  961. }, false);
  962. }
  963. }
  964. if(settings.closeOnEscape) {
  965. document.addEventListener('keyup', function (evt) {
  966. evt = evt || window.event;
  967. if(evt.keyCode == 27) {
  968. that.hide(settings, $DOM.toast, 'esc');
  969. }
  970. });
  971. }
  972. if(settings.closeOnClick) {
  973. $DOM.toast.addEventListener('click', function (evt) {
  974. that.hide(settings, $DOM.toast, 'toast');
  975. });
  976. }
  977. that.toast = $DOM.toast;
  978. };
  979. return $iziToast;
  980. });