Search code examples
javascriptjquerypopupsweetalertsweetalert2

Using SweetAlert2 as popup on page load


I am trying to use SweetAlert2 as a "popup box" once the page finishes loading. Underneath the "popup box" overlay is normal content.

  • The "popup box" will have 2 links that the visitor can click on.(clicking outside the box will not close the popup)
  • Upon clicking on any one of the link, it will open a respective new tab
  • If it detects visitor clicked on both links, it will unlock and redirect itself to another page.

How can I achieve this?

Reference:

How to add event listener for html buttons in sweetalert dialog box in jquery

`http://codepen.io/html5andblog/pen/jPzPWj` (this is good but it doesn't onload and redirect)

Solution

  • Here's your homework ;) [JSFIDDLE]

    swal({
      html: 
        '<a href="http://example1.com" id="link1" target="_blank">link 1</a><br>' + 
        '<a href="http://example2.com" id="link2" target="_blank">link 2</a>',
      confirmButtonText: 'Continue >',
      allowOutsideClick: false,
      allowEscapeKey: false
    });
    
    // disable "Continue >" button on load
    swal.disableButtons();
    
    // handle clicks and enable "Continue >" button when all links are clicked
    var clickedLinks = [];
    $('body').on('click', '.swal2-modal a', function(e) {
      var link = e.target;
      if (clickedLinks.indexOf(link) === -1) {
        clickedLinks.push(link);
      }
      // when all links are clicked enable "Continue >" button
      if (clickedLinks.length === $('.swal2-modal a').size()) {
        swal.enableButtons();
      }
    });