I want to create a while loop between 2 html page (Or a prompt where I can ask a question) and make so that if I give the wrong answer I get redirected to another HTML page that will remain for 5 seconds before getting back to the prompt.
I am trying the following code
<!DOCTYPE html>
<html>
<body>
<script>
var pass;
pass = prompt("The corret answer is 1");
if (pass == "1") {
document.location.href = "https://stackoverflow.com/questions/40539097/redirect-user-to-another-html-page-if-the-condition-is-true";
} else {
setTimeout(function(){
window.location.href = 'prova2.html';
}, 5000);
}
</script>
<body>
</html>
The Problem is that the page "prova2.html" came out after 5 second. Instead I want that it remain visible for 5 seconds.
CodePudding user response:
But that's exactly what your code does: if the result of prompt is '1' it redirects to SO, otherwise you start a timer that redirects to prova2 after 5 seconds.
If you want the behaviour you're describing, you need to redirect to prova2.html
immediately and in the code for prova2.html
you need to set a timeout that redirects you back after 5 seconds:
in original.html
(or whatever it's called for you):
<!DOCTYPE html>
<html>
<body>
<script>
var pass = prompt("The corret answer is 1");
if (pass == "1") {
document.location.href = "https://stackoverflow.com/questions/40539097/redirect-user-to-another-html-page-if-the-condition-is-true";
} else {
document.location.href = 'prova2.html';
}
</script>
<body>
</html>
in prova2.html
:
<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(() => {
document.location.href = 'original.html';
}, 5000)
</script>
<body>
</html>
CodePudding user response:
This example of prova2.html does not rely on filenames, it uses the session history of the browser:
<!DOCTYPE html>
<html>
<body>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
setTimeout(function(){
history.back();
//window.location.href = 'previous.html';
}, 5000);
});
</script>
<p>5 sec after pageload you should get redirected back</p>
<body>
</html>
Source: https://developer.mozilla.org/en-US/docs/Web/API/History/back