How to redirect the page only after confirmation?

Asked

Viewed 596 times

1

The user will click on a link and a confirmation message such as "Do you really want to access this page?" should appear. If he confirms, he is redirected, if he denies anything happens.

How can I do this?

$(document).ready(function() {
  $("a").click(function(evento) {
    confirm("tem certeza?");

    // E AGORA, COMO REDIRECIONO?
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="https://google.com">Ir para o Google.com</a>

  • confirm already returns you a Boleano, if it is not true evento.preventDefault(); blocks the following event.

2 answers

2

Try it like this:

$(document).ready(function(){
    $("a").click(function(evento){
        if(confirm("tem certeza?")){      
            window.location.href="http://www.google.com";
        }
    });
})

2


In your case, as the element is already a hyperlink, just capture the return of the confirm and prevent the default behavior of the browser (access link) if the return value is false.

Technically this is not a redirect, it’s just an interruption (in case user press the button Not) than would normally happen.

$(document).ready(function() {
  $("a").click(function(evento) {

    if (!confirm("Tem certeza?"))
      evento.preventDefault();
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="https://google.com">Ir para o Google.com</a>

If you want to simulate the behavior of an http redirect, prevent the default behavior of browser (again, since it is a hyperlink) and use window.location.replace.

You can also use window.location.href (or simply window.location), mentioned in the reply of @Paul Polidoro , both do virtually the same thing as navigating to the specified URL.

The difference is that window.location.replace does not include the URL in the history.

$(document).ready(function() {
  $("a").click(function(evento) {
    evento.preventDefault();
    if (confirm("Tem certeza?"))
      window.location.replace($(this).attr('href'));
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="https://google.com">Ir para o Google.com</a>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.