Sweetalert: Go to link on click OK

Created on 28 Oct 2014  ·  4Comments  ·  Source: t4t5/sweetalert

Forgive my inexperience. How can I achieve this:

I'd like sweetalert to show a message when a user clicks a link, but then to only go to the link _if_ the user selects 'OK' in the sweetalert dialog.

Thanks!

Most helpful comment

This is actually very simple to achieve. I'm using jQuery in this example.

$('a').click(function(e){
    e.preventDefault();
    var link = $(this).attr('href');

    swal({
        title: "Are you sure?",
        text: "By clicking 'OK' you will be redirected to the link.",
        type: "warning",
        showCancelButton: true
    },
    function(){
        window.location.href = link;
    });
});

This will add the behaviour to all a-tags. If you want it for certain links only, you could add a specific class to the a-tags, and limit the sweetAlert functionality to just them.

All 4 comments

The library do not have the option to do that. I modify the constructor in #165 (We need to wait to be approved) for sending an extra param to the constroctor, in this case it will be the link.

This is actually very simple to achieve. I'm using jQuery in this example.

$('a').click(function(e){
    e.preventDefault();
    var link = $(this).attr('href');

    swal({
        title: "Are you sure?",
        text: "By clicking 'OK' you will be redirected to the link.",
        type: "warning",
        showCancelButton: true
    },
    function(){
        window.location.href = link;
    });
});

This will add the behaviour to all a-tags. If you want it for certain links only, you could add a specific class to the a-tags, and limit the sweetAlert functionality to just them.

Thanks for you help Tristan, that works perfectly!

it's not working!

Uncaught SweetAlert: Unexpected 2nd argument (function(){
window.location.href = mainURL;

});

what should i do?

Was this page helpful?
0 / 5 - 0 ratings