nauti nauti - 27 days ago 12
Javascript Question

Login Page like Google with working back button

I have an login page and if the user enteres its username a post request to the server validates the username and provides an appropriate response.
If the username was valid a new input field for the password appears. I want the user to be able to go back to the input for the username but because I'm using ajax and javascript to display the new input field for the password after the username was validated, the back button just skips the username input.

The behavior of Googles login page when one presses the back button after entering the email and is "redirected" to the password input is exactly what I want.

How can I achieve the same behavior?

Thanks.

Answer

When you enter email id the gmail url is like:

https://accounts.google.com/ServiceLogin?sacu=1&scc=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&osid=1&service=mail&ss=1&ltmpl=default&rm=false#identifier

And when password:

https://accounts.google.com/ServiceLogin?sacu=1&scc=1&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&osid=1&service=mail&ss=1&ltmpl=default&rm=false#password

Look the change is only the hash tag at the very end of the url. Now how 'll you implement this?

There is a event in javascript called "hashchange".

Take a look at this:

<html>
<head>
    <title>Text</title>
</head>

<body>

    <div id="uname">
        //username related code


        <a href="#password"><div id="hello">Next</div></a>
    </div>


    <div id="password" style="display:none">
        //username related code


        <div id="final">Submit</div>
    </div>

    <script>

        window.onload=function(){

                window.addEventListener("hashchange", function(){                                               //this is the trick
                        console.log("Hash changed to", window.location.hash);

                        if(window.location.hash=="password")
                            //show password related div
                        else
                            //show username related div
                    });
            }

    </script>
</body>