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>
confirm already returns you a Boleano, if it is not true
evento.preventDefault()
; blocks the following event.– Marconi