How to run a SweetAlert instead of default javascript confirm method

Knut Pedersen picture Knut Pedersen · Jul 15, 2015 · Viewed 9k times · Source

Currently this is the code I use to run a normal confirm window based on the class "confirmation". This is all done with an href link and not on a button onClick event. As the result of the click is to run another code snipped placed in a different file (with the intention to delete a row in db).

$('.confirmation').on('click', function () {
        return confirm('Er du sikker på at du vil slette?');
    });

What I want is to replace the confirm method with this SweetAlert function

Anyone know how to do this, what happens when I try to place the sweetalert inside the onClick function is that the alert appears but it automatically delete the row without me having to confirm anything and the alert fades out.

Answer

Knut Pedersen picture Knut Pedersen · Jul 15, 2015

I found the solution!

$('.confirmation').click(function(e) {
e.preventDefault(); // Prevent the href from redirecting directly
var linkURL = $(this).attr("href");
warnBeforeRedirect(linkURL);
});

 function warnBeforeRedirect(linkURL) {
    swal({
      title: "Leave this site?", 
      text: "If you click 'OK', you will be redirected to " + linkURL, 
      type: "warning",
      showCancelButton: true
    }, function() {
      // Redirect the user
      window.location.href = linkURL;
    });
  }