/MakoKom.Web/Scripts/sweetalert/sweet-alert.js

https://bitbucket.org/marjante/makokom · JavaScript · 818 lines · 601 code · 129 blank · 88 comment · 136 complexity · 36039ae934fd34fc38289caa8e1665af MD5 · raw file

  1. // SweetAlert
  2. // 2014 (c) - Tristan Edwards
  3. // github.com/t4t5/sweetalert
  4. ;(function(window, document, undefined) {
  5. var modalClass = '.sweet-alert',
  6. overlayClass = '.sweet-overlay',
  7. alertTypes = ['error', 'warning', 'info', 'success'],
  8. defaultParams = {
  9. title: '',
  10. text: '',
  11. type: null,
  12. allowOutsideClick: false,
  13. showCancelButton: false,
  14. closeOnConfirm: true,
  15. closeOnCancel: true,
  16. confirmButtonText: 'OK',
  17. confirmButtonColor: '#AEDEF4',
  18. cancelButtonText: 'Cancel',
  19. imageUrl: null,
  20. imageSize: null,
  21. timer: null,
  22. customClass: '',
  23. html: false,
  24. animation: true,
  25. allowEscapeKey: true
  26. };
  27. /*
  28. * Manipulate DOM
  29. */
  30. var getModal = function() {
  31. var $modal = document.querySelector(modalClass);
  32. if (!$modal) {
  33. sweetAlertInitialize();
  34. $modal = getModal();
  35. }
  36. return $modal;
  37. },
  38. getOverlay = function() {
  39. return document.querySelector(overlayClass);
  40. },
  41. hasClass = function(elem, className) {
  42. return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
  43. },
  44. addClass = function(elem, className) {
  45. if (!hasClass(elem, className)) {
  46. elem.className += ' ' + className;
  47. }
  48. },
  49. removeClass = function(elem, className) {
  50. var newClass = ' ' + elem.className.replace(/[\t\r\n]/g, ' ') + ' ';
  51. if (hasClass(elem, className)) {
  52. while (newClass.indexOf(' ' + className + ' ') >= 0) {
  53. newClass = newClass.replace(' ' + className + ' ', ' ');
  54. }
  55. elem.className = newClass.replace(/^\s+|\s+$/g, '');
  56. }
  57. },
  58. escapeHtml = function(str) {
  59. var div = document.createElement('div');
  60. div.appendChild(document.createTextNode(str));
  61. return div.innerHTML;
  62. },
  63. _show = function(elem) {
  64. elem.style.opacity = '';
  65. elem.style.display = 'block';
  66. },
  67. show = function(elems) {
  68. if (elems && !elems.length) {
  69. return _show(elems);
  70. }
  71. for (var i = 0; i < elems.length; ++i) {
  72. _show(elems[i]);
  73. }
  74. },
  75. _hide = function(elem) {
  76. elem.style.opacity = '';
  77. elem.style.display = 'none';
  78. },
  79. hide = function(elems) {
  80. if (elems && !elems.length) {
  81. return _hide(elems);
  82. }
  83. for (var i = 0; i < elems.length; ++i) {
  84. _hide(elems[i]);
  85. }
  86. },
  87. isDescendant = function(parent, child) {
  88. var node = child.parentNode;
  89. while (node !== null) {
  90. if (node === parent) {
  91. return true;
  92. }
  93. node = node.parentNode;
  94. }
  95. return false;
  96. },
  97. getTopMargin = function(elem) {
  98. elem.style.left = '-9999px';
  99. elem.style.display = 'block';
  100. var height = elem.clientHeight,
  101. padding;
  102. if (typeof getComputedStyle !== "undefined") { /* IE 8 */
  103. padding = parseInt(getComputedStyle(elem).getPropertyValue('padding'), 10);
  104. } else {
  105. padding = parseInt(elem.currentStyle.padding);
  106. }
  107. elem.style.left = '';
  108. elem.style.display = 'none';
  109. return ('-' + parseInt(height / 2 + padding) + 'px');
  110. },
  111. fadeIn = function(elem, interval) {
  112. if (+elem.style.opacity < 1) {
  113. interval = interval || 16;
  114. elem.style.opacity = 0;
  115. elem.style.display = 'block';
  116. var last = +new Date();
  117. var tick = function() {
  118. elem.style.opacity = +elem.style.opacity + (new Date() - last) / 100;
  119. last = +new Date();
  120. if (+elem.style.opacity < 1) {
  121. setTimeout(tick, interval);
  122. }
  123. };
  124. tick();
  125. }
  126. elem.style.display = 'block'; //fallback IE8
  127. },
  128. fadeOut = function(elem, interval) {
  129. interval = interval || 16;
  130. elem.style.opacity = 1;
  131. var last = +new Date();
  132. var tick = function() {
  133. elem.style.opacity = +elem.style.opacity - (new Date() - last) / 100;
  134. last = +new Date();
  135. if (+elem.style.opacity > 0) {
  136. setTimeout(tick, interval);
  137. } else {
  138. elem.style.display = 'none';
  139. }
  140. };
  141. tick();
  142. },
  143. fireClick = function(node) {
  144. // Taken from http://www.nonobtrusive.com/2011/11/29/programatically-fire-crossbrowser-click-event-with-javascript/
  145. // Then fixed for today's Chrome browser.
  146. if (typeof MouseEvent === 'function') {
  147. // Up-to-date approach
  148. var mevt = new MouseEvent('click', {
  149. view: window,
  150. bubbles: false,
  151. cancelable: true
  152. });
  153. node.dispatchEvent(mevt);
  154. } else if ( document.createEvent ) {
  155. // Fallback
  156. var evt = document.createEvent('MouseEvents');
  157. evt.initEvent('click', false, false);
  158. node.dispatchEvent(evt);
  159. } else if( document.createEventObject ) {
  160. node.fireEvent('onclick') ;
  161. } else if (typeof node.onclick === 'function' ) {
  162. node.onclick();
  163. }
  164. },
  165. stopEventPropagation = function(e) {
  166. // In particular, make sure the space bar doesn't scroll the main window.
  167. if (typeof e.stopPropagation === 'function') {
  168. e.stopPropagation();
  169. e.preventDefault();
  170. } else if (window.event && window.event.hasOwnProperty('cancelBubble')) {
  171. window.event.cancelBubble = true;
  172. }
  173. };
  174. // Remember state in cases where opening and handling a modal will fiddle with it.
  175. var previousActiveElement,
  176. previousDocumentClick,
  177. previousWindowKeyDown,
  178. lastFocusedButton;
  179. /*
  180. * Add modal + overlay to DOM
  181. */
  182. window.sweetAlertInitialize = function() {
  183. var sweetHTML = '<div class="sweet-overlay" tabIndex="-1"></div><div class="sweet-alert" tabIndex="-1"><div class="icon error"><span class="x-mark"><span class="line left"></span><span class="line right"></span></span></div><div class="icon warning"> <span class="body"></span> <span class="dot"></span> </div> <div class="icon info"></div> <div class="icon success"> <span class="line tip"></span> <span class="line long"></span> <div class="placeholder"></div> <div class="fix"></div> </div> <div class="icon custom"></div> <h2>Title</h2><p>Text</p><button class="cancel" tabIndex="2">Cancel</button><button class="confirm" tabIndex="1">OK</button></div>',
  184. sweetWrap = document.createElement('div');
  185. sweetWrap.innerHTML = sweetHTML;
  186. // Append elements to body
  187. while (sweetWrap.firstChild) {
  188. document.body.appendChild(sweetWrap.firstChild);
  189. }
  190. };
  191. /*
  192. * Global sweetAlert function
  193. */
  194. window.sweetAlert = window.swal = function() {
  195. // Copy arguments to the local args variable
  196. var args = arguments;
  197. if (getModal() !== null) {
  198. // If getModal returns values then continue
  199. modalDependant.apply(this, args);
  200. } else {
  201. // If getModal returns null i.e. no matches, then set up a interval event to check the return value until it is not null
  202. var modalCheckInterval = setInterval(function() {
  203. if (getModal() !== null) {
  204. clearInterval(modalCheckInterval);
  205. modalDependant.apply(this, args);
  206. }
  207. }, 100);
  208. }
  209. };
  210. function modalDependant() {
  211. var customizations = arguments[0];
  212. /*
  213. * Use argument if defined or default value from params object otherwise.
  214. * Supports the case where a default value is boolean true and should be
  215. * overridden by a corresponding explicit argument which is boolean false.
  216. */
  217. function argumentOrDefault(key) {
  218. var args = customizations;
  219. if (typeof args[key] !== 'undefined') {
  220. return args[key];
  221. } else {
  222. return defaultParams[key];
  223. }
  224. }
  225. if (arguments[0] === undefined) {
  226. logStr('SweetAlert expects at least 1 attribute!');
  227. return false;
  228. }
  229. var params = extend({}, defaultParams);
  230. switch (typeof arguments[0]) {
  231. // Ex: swal("Hello", "Just testing", "info");
  232. case 'string':
  233. params.title = arguments[0];
  234. params.text = arguments[1] || '';
  235. params.type = arguments[2] || '';
  236. break;
  237. // Ex: swal({title:"Hello", text: "Just testing", type: "info"});
  238. case 'object':
  239. if (arguments[0].title === undefined) {
  240. logStr('Missing "title" argument!');
  241. return false;
  242. }
  243. params.title = arguments[0].title;
  244. var availableCustoms = [
  245. 'text',
  246. 'type',
  247. 'customClass',
  248. 'allowOutsideClick',
  249. 'showCancelButton',
  250. 'closeOnConfirm',
  251. 'closeOnCancel',
  252. 'timer',
  253. 'confirmButtonColor',
  254. 'cancelButtonText',
  255. 'imageUrl',
  256. 'imageSize',
  257. 'html',
  258. 'animation',
  259. 'allowEscapeKey'];
  260. // It would be nice to just use .forEach here, but IE8... :(
  261. var numCustoms = availableCustoms.length;
  262. for (var customIndex = 0; customIndex < numCustoms; customIndex++) {
  263. var customName = availableCustoms[customIndex];
  264. params[customName] = argumentOrDefault(customName);
  265. }
  266. // Show "Confirm" instead of "OK" if cancel button is visible
  267. params.confirmButtonText = (params.showCancelButton) ? 'Confirm' : defaultParams.confirmButtonText;
  268. params.confirmButtonText = argumentOrDefault('confirmButtonText');
  269. // Function to call when clicking on cancel/OK
  270. params.doneFunction = arguments[1] || null;
  271. break;
  272. default:
  273. logStr('Unexpected type of argument! Expected "string" or "object", got ' + typeof arguments[0]);
  274. return false;
  275. }
  276. setParameters(params);
  277. fixVerticalPosition();
  278. openModal();
  279. // Modal interactions
  280. var modal = getModal();
  281. // Mouse interactions
  282. var onButtonEvent = function(event) {
  283. var e = event || window.event;
  284. var target = e.target || e.srcElement,
  285. targetedConfirm = (target.className.indexOf("confirm") !== -1),
  286. modalIsVisible = hasClass(modal, 'visible'),
  287. doneFunctionExists = (params.doneFunction && modal.getAttribute('data-has-done-function') === 'true');
  288. switch (e.type) {
  289. case ("mouseover"):
  290. if (targetedConfirm) {
  291. target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.04);
  292. }
  293. break;
  294. case ("mouseout"):
  295. if (targetedConfirm) {
  296. target.style.backgroundColor = params.confirmButtonColor;
  297. }
  298. break;
  299. case ("mousedown"):
  300. if (targetedConfirm) {
  301. target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.14);
  302. }
  303. break;
  304. case ("mouseup"):
  305. if (targetedConfirm) {
  306. target.style.backgroundColor = colorLuminance(params.confirmButtonColor, -0.04);
  307. }
  308. break;
  309. case ("focus"):
  310. var $confirmButton = modal.querySelector('button.confirm'),
  311. $cancelButton = modal.querySelector('button.cancel');
  312. if (targetedConfirm) {
  313. $cancelButton.style.boxShadow = 'none';
  314. } else {
  315. $confirmButton.style.boxShadow = 'none';
  316. }
  317. break;
  318. case ("click"):
  319. if (targetedConfirm && doneFunctionExists && modalIsVisible) { // Clicked "confirm"
  320. params.doneFunction(true);
  321. if (params.closeOnConfirm) {
  322. window.sweetAlert.close();
  323. }
  324. } else if (doneFunctionExists && modalIsVisible) { // Clicked "cancel"
  325. // Check if callback function expects a parameter (to track cancel actions)
  326. var functionAsStr = String(params.doneFunction).replace(/\s/g, '');
  327. var functionHandlesCancel = functionAsStr.substring(0, 9) === "function(" && functionAsStr.substring(9, 10) !== ")";
  328. if (functionHandlesCancel) {
  329. params.doneFunction(false);
  330. }
  331. if (params.closeOnCancel) {
  332. window.sweetAlert.close();
  333. }
  334. } else {
  335. window.sweetAlert.close();
  336. }
  337. break;
  338. }
  339. };
  340. var $buttons = modal.querySelectorAll('button');
  341. for (var i = 0; i < $buttons.length; i++) {
  342. $buttons[i].onclick = onButtonEvent;
  343. $buttons[i].onmouseover = onButtonEvent;
  344. $buttons[i].onmouseout = onButtonEvent;
  345. $buttons[i].onmousedown = onButtonEvent;
  346. //$buttons[i].onmouseup = onButtonEvent;
  347. $buttons[i].onfocus = onButtonEvent;
  348. }
  349. // Remember the current document.onclick event.
  350. previousDocumentClick = document.onclick;
  351. document.onclick = function(event) {
  352. var e = event || window.event;
  353. var target = e.target || e.srcElement;
  354. var clickedOnModal = (modal === target),
  355. clickedOnModalChild = isDescendant(modal, target),
  356. modalIsVisible = hasClass(modal, 'visible'),
  357. outsideClickIsAllowed = modal.getAttribute('data-allow-ouside-click') === 'true';
  358. if (!clickedOnModal && !clickedOnModalChild && modalIsVisible && outsideClickIsAllowed) {
  359. window.sweetAlert.close();
  360. }
  361. };
  362. // Keyboard interactions
  363. var $okButton = modal.querySelector('button.confirm'),
  364. $cancelButton = modal.querySelector('button.cancel'),
  365. $modalButtons = modal.querySelectorAll('button[tabindex]');
  366. function handleKeyDown(event) {
  367. var e = event || window.event;
  368. var keyCode = e.keyCode || e.which;
  369. if ([9,13,32,27].indexOf(keyCode) === -1) {
  370. // Don't do work on keys we don't care about.
  371. return;
  372. }
  373. var $targetElement = e.target || e.srcElement;
  374. var btnIndex = -1; // Find the button - note, this is a nodelist, not an array.
  375. for (var i = 0; i < $modalButtons.length; i++) {
  376. if ($targetElement === $modalButtons[i]) {
  377. btnIndex = i;
  378. break;
  379. }
  380. }
  381. if (keyCode === 9) {
  382. // TAB
  383. if (btnIndex === -1) {
  384. // No button focused. Jump to the confirm button.
  385. $targetElement = $okButton;
  386. } else {
  387. // Cycle to the next button
  388. if (btnIndex === $modalButtons.length - 1) {
  389. $targetElement = $modalButtons[0];
  390. } else {
  391. $targetElement = $modalButtons[btnIndex + 1];
  392. }
  393. }
  394. stopEventPropagation(e);
  395. $targetElement.focus();
  396. setFocusStyle($targetElement, params.confirmButtonColor); // TODO
  397. } else {
  398. if (keyCode === 13 || keyCode === 32) {
  399. if (btnIndex === -1) {
  400. // ENTER/SPACE clicked outside of a button.
  401. $targetElement = $okButton;
  402. } else {
  403. // Do nothing - let the browser handle it.
  404. $targetElement = undefined;
  405. }
  406. } else if (keyCode === 27 && params.allowEscapeKey === true) {
  407. $targetElement = $cancelButton;
  408. } else {
  409. // Fallback - let the browser handle it.
  410. $targetElement = undefined;
  411. }
  412. if ($targetElement !== undefined) {
  413. fireClick($targetElement, e);
  414. }
  415. }
  416. }
  417. previousWindowKeyDown = window.onkeydown;
  418. window.onkeydown = handleKeyDown;
  419. function handleOnBlur(event) {
  420. var e = event || window.event;
  421. var $targetElement = e.target || e.srcElement,
  422. $focusElement = e.relatedTarget,
  423. modalIsVisible = hasClass(modal, 'visible');
  424. if (modalIsVisible) {
  425. var btnIndex = -1; // Find the button - note, this is a nodelist, not an array.
  426. if ($focusElement !== null) {
  427. // If we picked something in the DOM to focus to, let's see if it was a button.
  428. for (var i = 0; i < $modalButtons.length; i++) {
  429. if ($focusElement === $modalButtons[i]) {
  430. btnIndex = i;
  431. break;
  432. }
  433. }
  434. if (btnIndex === -1) {
  435. // Something in the dom, but not a visible button. Focus back on the button.
  436. $targetElement.focus();
  437. }
  438. } else {
  439. // Exiting the DOM (e.g. clicked in the URL bar);
  440. lastFocusedButton = $targetElement;
  441. }
  442. }
  443. }
  444. $okButton.onblur = handleOnBlur;
  445. $cancelButton.onblur = handleOnBlur;
  446. window.onfocus = function() {
  447. // When the user has focused away and focused back from the whole window.
  448. window.setTimeout(function() {
  449. // Put in a timeout to jump out of the event sequence. Calling focus() in the event
  450. // sequence confuses things.
  451. if (lastFocusedButton !== undefined) {
  452. lastFocusedButton.focus();
  453. lastFocusedButton = undefined;
  454. }
  455. }, 0);
  456. };
  457. }
  458. /*
  459. * Set default params for each popup
  460. * @param {Object} userParams
  461. */
  462. window.sweetAlert.setDefaults = window.swal.setDefaults = function(userParams) {
  463. if (!userParams) {
  464. throw new Error('userParams is required');
  465. }
  466. if (typeof userParams !== 'object') {
  467. throw new Error('userParams has to be a object');
  468. }
  469. extend(defaultParams, userParams);
  470. };
  471. /*
  472. * Set type, text and actions on modal
  473. */
  474. function setParameters(params) {
  475. var modal = getModal();
  476. var $title = modal.querySelector('h2'),
  477. $text = modal.querySelector('p'),
  478. $cancelBtn = modal.querySelector('button.cancel'),
  479. $confirmBtn = modal.querySelector('button.confirm');
  480. // Title
  481. $title.innerHTML = (params.html) ? params.title : escapeHtml(params.title).split("\n").join("<br>");
  482. // Text
  483. $text.innerHTML = (params.html) ? params.text : escapeHtml(params.text || '').split("\n").join("<br>");
  484. if (params.text) {
  485. show($text);
  486. }
  487. //Custom Class
  488. if (params.customClass) {
  489. addClass(modal, params.customClass);
  490. modal.setAttribute('data-custom-class', params.customClass);
  491. } else {
  492. // Find previously set classes and remove them
  493. var customClass = modal.getAttribute('data-custom-class');
  494. removeClass(modal, customClass);
  495. modal.setAttribute('data-custom-class', "");
  496. }
  497. // Icon
  498. hide(modal.querySelectorAll('.icon'));
  499. if (params.type && !isIE8()) {
  500. var validType = false;
  501. for (var i = 0; i < alertTypes.length; i++) {
  502. if (params.type === alertTypes[i]) {
  503. validType = true;
  504. break;
  505. }
  506. }
  507. if (!validType) {
  508. logStr('Unknown alert type: ' + params.type);
  509. return false;
  510. }
  511. var $icon = modal.querySelector('.icon.' + params.type);
  512. show($icon);
  513. // Animate icon
  514. switch (params.type) {
  515. case "success":
  516. addClass($icon, 'animate');
  517. addClass($icon.querySelector('.tip'), 'animateSuccessTip');
  518. addClass($icon.querySelector('.long'), 'animateSuccessLong');
  519. break;
  520. case "error":
  521. addClass($icon, 'animateErrorIcon');
  522. addClass($icon.querySelector('.x-mark'), 'animateXMark');
  523. break;
  524. case "warning":
  525. addClass($icon, 'pulseWarning');
  526. addClass($icon.querySelector('.body'), 'pulseWarningIns');
  527. addClass($icon.querySelector('.dot'), 'pulseWarningIns');
  528. break;
  529. }
  530. }
  531. // Custom image
  532. if (params.imageUrl) {
  533. var $customIcon = modal.querySelector('.icon.custom');
  534. $customIcon.style.backgroundImage = 'url(' + params.imageUrl + ')';
  535. show($customIcon);
  536. var _imgWidth = 80,
  537. _imgHeight = 80;
  538. if (params.imageSize) {
  539. var dimensions = params.imageSize.toString().split('x');
  540. var imgWidth = dimensions[0];
  541. var imgHeight = dimensions[1];
  542. if (!imgWidth || !imgHeight) {
  543. logStr("Parameter imageSize expects value with format WIDTHxHEIGHT, got " + params.imageSize);
  544. } else {
  545. _imgWidth = imgWidth;
  546. _imgHeight = imgHeight;
  547. }
  548. }
  549. $customIcon.setAttribute('style', $customIcon.getAttribute('style') + 'width:' + _imgWidth + 'px; height:' + _imgHeight + 'px');
  550. }
  551. // Cancel button
  552. modal.setAttribute('data-has-cancel-button', params.showCancelButton);
  553. if (params.showCancelButton) {
  554. $cancelBtn.style.display = 'inline-block';
  555. } else {
  556. hide($cancelBtn);
  557. }
  558. // Edit text on cancel and confirm buttons
  559. if (params.cancelButtonText) {
  560. $cancelBtn.innerHTML = escapeHtml(params.cancelButtonText);
  561. }
  562. if (params.confirmButtonText) {
  563. $confirmBtn.innerHTML = escapeHtml(params.confirmButtonText);
  564. }
  565. // Set confirm button to selected background color
  566. $confirmBtn.style.backgroundColor = params.confirmButtonColor;
  567. // Set box-shadow to default focused button
  568. setFocusStyle($confirmBtn, params.confirmButtonColor);
  569. // Allow outside click?
  570. modal.setAttribute('data-allow-ouside-click', params.allowOutsideClick);
  571. // Done-function
  572. var hasDoneFunction = (params.doneFunction) ? true : false;
  573. modal.setAttribute('data-has-done-function', hasDoneFunction);
  574. // Prevent modal from animating
  575. if (!params.animation){
  576. modal.setAttribute('data-animation', 'none');
  577. } else{
  578. modal.setAttribute('data-animation', 'pop');
  579. }
  580. // Close timer
  581. modal.setAttribute('data-timer', params.timer);
  582. }
  583. /*
  584. * Set hover, active and focus-states for buttons (source: http://www.sitepoint.com/javascript-generate-lighter-darker-color)
  585. */
  586. function colorLuminance(hex, lum) {
  587. // Validate hex string
  588. hex = String(hex).replace(/[^0-9a-f]/gi, '');
  589. if (hex.length < 6) {
  590. hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  591. }
  592. lum = lum || 0;
  593. // Convert to decimal and change luminosity
  594. var rgb = "#", c, i;
  595. for (i = 0; i < 3; i++) {
  596. c = parseInt(hex.substr(i*2,2), 16);
  597. c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
  598. rgb += ("00"+c).substr(c.length);
  599. }
  600. return rgb;
  601. }
  602. function extend(a, b){
  603. for (var key in b) {
  604. if (b.hasOwnProperty(key)) {
  605. a[key] = b[key];
  606. }
  607. }
  608. return a;
  609. }
  610. function hexToRgb(hex) {
  611. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  612. return result ? parseInt(result[1], 16) + ', ' + parseInt(result[2], 16) + ', ' + parseInt(result[3], 16) : null;
  613. }
  614. // Add box-shadow style to button (depending on its chosen bg-color)
  615. function setFocusStyle($button, bgColor) {
  616. var rgbColor = hexToRgb(bgColor);
  617. $button.style.boxShadow = '0 0 2px rgba(' + rgbColor +', 0.8), inset 0 0 0 1px rgba(0, 0, 0, 0.05)';
  618. }
  619. // Animation when opening modal
  620. function openModal() {
  621. var modal = getModal();
  622. fadeIn(getOverlay(), 10);
  623. show(modal);
  624. addClass(modal, 'showSweetAlert');
  625. removeClass(modal, 'hideSweetAlert');
  626. previousActiveElement = document.activeElement;
  627. var $okButton = modal.querySelector('button.confirm');
  628. $okButton.focus();
  629. setTimeout(function() {
  630. addClass(modal, 'visible');
  631. }, 500);
  632. var timer = modal.getAttribute('data-timer');
  633. if (timer !== "null" && timer !== "") {
  634. modal.timeout = setTimeout(function() {
  635. window.sweetAlert.close();
  636. }, timer);
  637. }
  638. }
  639. // Aninmation when closing modal
  640. window.sweetAlert.close = window.swal.close = function() {
  641. var modal = getModal();
  642. fadeOut(getOverlay(), 5);
  643. fadeOut(modal, 5);
  644. removeClass(modal, 'showSweetAlert');
  645. addClass(modal, 'hideSweetAlert');
  646. removeClass(modal, 'visible');
  647. // Reset icon animations
  648. var $successIcon = modal.querySelector('.icon.success');
  649. removeClass($successIcon, 'animate');
  650. removeClass($successIcon.querySelector('.tip'), 'animateSuccessTip');
  651. removeClass($successIcon.querySelector('.long'), 'animateSuccessLong');
  652. var $errorIcon = modal.querySelector('.icon.error');
  653. removeClass($errorIcon, 'animateErrorIcon');
  654. removeClass($errorIcon.querySelector('.x-mark'), 'animateXMark');
  655. var $warningIcon = modal.querySelector('.icon.warning');
  656. removeClass($warningIcon, 'pulseWarning');
  657. removeClass($warningIcon.querySelector('.body'), 'pulseWarningIns');
  658. removeClass($warningIcon.querySelector('.dot'), 'pulseWarningIns');
  659. // Reset the page to its previous state
  660. window.onkeydown = previousWindowKeyDown;
  661. document.onclick = previousDocumentClick;
  662. if (previousActiveElement) {
  663. previousActiveElement.focus();
  664. }
  665. lastFocusedButton = undefined;
  666. clearTimeout(modal.timeout);
  667. };
  668. /*
  669. * Set "margin-top"-property on modal based on its computed height
  670. */
  671. function fixVerticalPosition() {
  672. var modal = getModal();
  673. modal.style.marginTop = getTopMargin(getModal());
  674. }
  675. // If browser is Internet Explorer 8
  676. function isIE8() {
  677. if (window.attachEvent && !window.addEventListener) {
  678. return true;
  679. } else {
  680. return false;
  681. }
  682. }
  683. // Error messages for developers
  684. function logStr(string) {
  685. if (window.console) { // IE...
  686. window.console.log("SweetAlert: " + string);
  687. }
  688. }
  689. })(window, document);