简体   繁体   中英

Div disappears after page load

I am new to jQuery and JavaScript and I'm stuck at a point, so I need suggestions from the intelligent brains sitting out there. I have div which is shown to the user before he logs in.

<div id="login" class = "login">
<ul>
  <li><a href="signup.html">Login</a></li>
</ul>
</div>

I want to replace this div with another div, which is hidden initially, after the user logs in successfully.

Div to be replaced with:

<div id="welcomelogin" class = "login" style="display: none;">
<ul>
  <li><a href="profile.html">Welcome abc</a></li>
</ul>
</div>

I am doing the following in my jQuery (right now I have hardcoded username/password values just to explain my problem).

I am calling auth function on a login button click. After the user clicks the login button, I want the page to reload and the #login div to be replaced with the #welcomeLogin div, so that the new url is shown to the user. But the problem is that the #welcomeLogin div does show up for few seconds, and then goes away because I have location.reload in place.

I also want the page to reload after authentication is successful, and then show the #welcomeLogin div until session remains. All this is done outside $( document ).ready();

function auth() {
    var userName = $("#login-username").val();
    var password = $("#login-password").val();

    if (userName == 'abc@xyz.com' && password == '12345') {
        location.reload();
        $("#login").hide();
        if (sessionStorage) {

            $("#welcomeLogin").show();
        }
    }
}

When you call location.reload() , the page refreshes. That means anything else on the client (ie any proceding javascript) may have time to run, but it's only because of the time the browser takes in refreshing the page.

You may call this javascript function on page load, and monitor some sort of state if you wish to seemingly 'persist' some change of DOM (swapping of divs, for example) to the next 'version' of the page.

I'd like to follow up with a recommended (alternative) way of doing this in javascript, but quite honestly I'm not sure it's the best approach at all for authentication.

I'd recommend a form post, and there are already available components for implementing form-based authentication depending on what you have on the server.

After you refesh you page, everything goes to the very begining. your auth function will stop then and every js file are reloaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM