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>