1

I have a jQuery function that triggers an alert pop-up when clicked. I need a another event to trigger when that OK button is hit. In this case the user is agreeing to something, I need to store a variable to localstorage that they agreed. My current code for alert:

$('.external').click( function() { alert("You are now leaving site"); });
Sam
  • 5,150
  • 4
  • 30
  • 51
  • 1
    Use a `confirm` box: https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm – Rory McCrossan Jun 26 '15 at 17:42
  • I suggest you should create a modal for the first alert and then on OK click , show the window alert. – Sajal Jun 26 '15 at 17:43
  • as for the localstorage part of the question, check [this](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) out – Frank Bryce Jun 26 '15 at 17:46

1 Answers1

4

You're looking for confirm(). Try this:

$('.external').click(function (e) {
    var r = confirm("You are now leaving site");
    if (r == true) {
        // user agreed, do something 
    } else {
        // user did not agree, do something else
    }
    e.preventDefault();
});

EDIT 1:

As per @JohnCarpenter, regarding localStorage: Storing Objects in HTML5 localStorage

EDIT 2:

To redirect the page upon confirmation, use something like this:

window.location.replace("http://domain.com");

You could also get fancy with jQuery and get the URL dynamically from the original anchor's href attribute:

window.location.replace($(this).prop('href'));

Please also see this post regarding window.location.replace. It's possible that window.location.href would better suit your needs.

Community
  • 1
  • 1
Stuart Wagner
  • 1,997
  • 1
  • 14
  • 22
  • good answer, for the localstorage part of the question, [this stack overflow link](http://stackoverflow.com/questions/2010892/storing-objects-in-html5-localstorage) is a good one. – Frank Bryce Jun 26 '15 at 17:47
  • @Stuart Good answer. When using confirm() what is the correct way to not follow the link if user selects cancel? – Sam Jun 26 '15 at 17:49
  • @Sam Adding `e.preventDefault();` while passing the closure within the `click` call an event object (`e`) will prevent the browser's default behavior of navigating to the link. I've updated my answer to reflect this. – Stuart Wagner Jun 26 '15 at 17:53
  • @Staurt e.preventDefault(); stops the link, how would allow it if r== true? – Sam Jun 26 '15 at 17:58