How to redirect the page only after confirmation?

1

The user will click on a link and a confirmation message like "Do you really want to access this page?" appears. If it confirms it, it is redirected, if it deny nothing 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><ahref="https://google.com">Ir para o Google.com</a>
    
asked by anonymous 01.03.2016 / 16:29

2 answers

2

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

Technically this is not a redirect, it is just an interrupt (if user press the No button) 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><ahref="https://google.com">Ir para o Google.com</a>

If you want to simulate the behavior of an http redirect, prevent the default browser behavior (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 Paul Polidoro response, both do pretty much 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><ahref="https://google.com">Ir para o Google.com</a>
    
01.03.2016 / 16:53
2

Try this:

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