Maintaining the original layout upon refreshing the page

Incorporating two forms on my website, I added a button that transitions between the login and sign-up forms smoothly. The process is as follows:

  1. Initially, the login form is displayed; clicking the button switches to the sign-up form.
  2. Proceeding to submit the sign-up form causes a page reload.
  3. Upon reload, the login form reappears by default.

The issue arises when I desire the last active form to remain displayed even after the page refreshes.

HTML:

<section id="content">
    <div id="logo" style="margin-left: 0;"></div>
    <div id="container">
        <form id="sign_up" action="login.php" method="post">
            <table style="margin: 0px auto;">
                <tr>
                    <td align="center"> <span style="font-weight: bold;font-size: 2em; color: Gray;">Sign Up</span>

                    </td>
                    <tr>
                        <td>
                            <input type="text" placeholder="Username" name="username" required="required" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="password" placeholder="Password" name="password" required="required" />
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input class="input" type="password" placeholder="Confirm Password" name="confirm_password" required="required" />
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <br/>
                        </td>
                    </tr>
                    <tr align="right">
                        <td>
                            <input class="btn" type="submit" value="Sign Up" name="submit_sign_up">
                        </td>
                    </tr>
            </table>
        </form>
        <form id="sign_in" action="login.php" method="post">
            <table style="margin: 0 auto;">
                <tr>
                    <td align="center"> <span style="font-weight: bold;font-size: 2em; color: Gray;">Sign In</span>

                    </td>
                    <tr>
                        <td>
                            <input class="input" type="text" placeholder="Username" name="username" required="required" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input class="input" type="password" placeholder="Password" name="password" required="required" />
                            <br />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <br/>
                        </td>
                    </tr>
                    <tr align="right">
                        <td>
                            <input class="btn" type="submit" value="Sign In" name="submit_sign_in">
                        </td>
                    </tr>
            </table>
        </form>
        <br/>
        <input id="sign_up_btn" class="btn" type="submit" style=" font-weight:bold; height:40px; width: 292px;" value="Create An Account"></input>
    </div>
</section>

CSS:

#content {
    margin-top: 10%;
}
#container {
    margin: 0 auto;
    width: 80%;
    text-align: center;
}
input[type=text], input[type=password] {
    width: 250px;
    min-height: 25px;
    border-radius: 3px;
    border: 0;
    padding: 7px;
    font-family: Calibri;
    font-size: 20px;
    box-shadow: 0px 0px 3px 1px #aaa inset;
    box-sizing: border-box;
}
#sign_in, #sign_up {
    border: 1px solid #4f4f4f;
    border-radius: 10px;
    margin: 0 auto;
    height: 200px;
    width: 292px;
    padding: 10px;
    background-color: #eee;
    border: 0px;
    box-shadow: 0px 0px 15px 1px #000;
}
#sign_up {
    display: none;
    height: 250px;
}

JS:

jQuery(function ($) {

    var $sUp = $("#sign_up"),
        $sIn = $("#sign_in");

    $("#content").on('click', "#sign_up_btn", function () {

        $sIn.stop().fadeOut(800, function () {
            $sUp.fadeIn(800);
        });
        $(this).stop().fadeOut(800, function () {
            $(this).attr({
                value: "Already have an account?",
                id: "sign_in_btn"
            }).fadeIn(800);
        });

    }).on('click', "#sign_in_btn", function () {

        $sUp.stop().fadeOut(800, function () {
            $sIn.fadeIn(800);
        });
        $(this).stop().fadeOut(800, function () {
            $(this).attr({
                value: "Create An Account",
                id: "sign_up_btn"
            }).fadeIn(800);
        });

    });

});

Answer №1

To efficiently save the form state, consider using either localStorage or sessionStorage. If you plan on expanding this functionality, it may be beneficial to explore frameworks that specialize in managing page states.

The script below demonstrates how to set the value of lastForm in localStorage within each event handler. It checks if localStorage.lastForm is equal to sign_up, and changes the current form accordingly.

jQuery(function ($) {

    var $sUp = $("#sign_up"),
        $sIn = $("#sign_in");

    $("#content").on('click', "#sign_up_btn", function () {

        $sIn.stop().fadeOut(800, function () {
            $sUp.fadeIn(800);
        });
        $(this).stop().fadeOut(800, function () {
            $(this).attr({
                value: "Already have an account?",
                id: "sign_in_btn"
            }).fadeIn(800);
        });
        localStorage.lastForm = 'sign_up';
    }).on('click', "#sign_in_btn", function () {

        $sUp.stop().fadeOut(800, function () {
            $sIn.fadeIn(800);
        });
        $(this).stop().fadeOut(800, function () {
            $(this).attr({
                value: "Create An Account",
                id: "sign_up_btn"
            }).fadeIn(800);
        });
        localStorage.lastForm = 'sign_in';
    });

    if (localStorage.lastForm == 'sign_up') {
        $sIn.fadeOut(0);
        $sUp.fadeIn(0);
    }
});

Check out a live example on jsFiddle!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem with using .append and .prepend

Hey there! I've encountered a strange issue while using the .append and .prepend methods in JQuery. I'm quite familiar with these methods, but something odd is happening when I implement this code: $("#nashgraphics-menu ul li a.toplevel-a") .pr ...

PHP encountered an error while encoding JSON: The final record is empty

I am currently facing an issue while attempting to read a file using ajax. After some troubleshooting, I encountered the following error: SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 48 of the JSON data. U ...

Choose various selections from a drop-down menu using AngularJs

I am currently working on a project where I need to be able to select multiple options from a dropdown menu. The code snippet for this functionality looks like the following: //Controller $scope.data = [{id: 1, Country: Zambia}, {id: 2, Coun ...

Interactive Range Slider for Scrolling Through Div Content

I am currently facing an issue where I want to implement a HTML range slider for controlling the horizontal scrolling of a div located below. This functionality is similar to that of a scroll bar, but it will be positioned away from the scrollable content ...

React Redux is facing difficulties resolving its own modules

Upon running webpack for my project, an error regarding the React-Redux package not being able to resolve some of its internal modules has been encountered: ERROR in ./node_modules/react-redux/es/index.js Module not found: Error: Can't resolve ' ...

What is the best way to merge angularjs modules?

In my angularjs application using the codeigniter PHP framework, I have implemented 3 modules - cars.js for car details, cellphones.js for cellphone details, and home.js for home details. Each module caters to a different client's needs. I am trying ...

Encountering a "DOM Exception 11: InvalidStateError" when attempting to use websocket.send

I encountered the following error message: DOM Invalidate exception 11 This error is coming from the code snippet below, but I'm having trouble identifying the root cause. /*The coding style may appear pseudo-stylish with potential syntax errors*/ ...

Nextjs couldn't locate the requested page

After creating a new Next.js application, I haven't made any changes to the code yet. However, when I try to run "npm run dev," it shows me the message "ready started server on [::]:3000, url: http://localhost:3000." But when I attempt to access it, I ...

Modify table row background color using PHP based on its position in the table with the use of a function

I am having trouble formatting my table to highlight different rows in distinct colors. The top row should be one color, the second row another, and the bottom two rows a different color each. This is to represent winners, teams getting promoted, and tho ...

Prevent redundant Webpack chunk creation

I am currently working on integrating a new feature into my Webpack project, and I have encountered a specific issue. Within the project, there are two entry points identified as about and feedback. The about entry point imports feedback, causing both abo ...

Utilizing Jquery's .GET method to retrieve and handle JSON data

In the jQuery snippet below, I am trying to fetch product data from . However, I am facing difficulty in iterating through the loop to access all 30 products along with their details. $.get("https://dummyjson.com/products/1") .done(function ...

What causes the order of `on` handler calls to be unpredictable in Angular?

Below is the code snippet I have been working on function linkFunc(scope, element, attr){ var clickedElsewhere = false; $document.on('click', function(){ clickedElsewhere = false; console.log('i ...

Implementing the session injection into a request body within an asynchronous function in Node.js

I've been trying to inject a session value into the request in order to use it in various parts of my app. What I'm currently attempting is to call a function by providing an ID to search for a user in the database and retrieve the name of that s ...

Displaying a Bootstrap button and an input box next to each other

Looking for advice on aligning or arranging a button and input box side by side in Bootstrap without grouping. I've searched online for examples, but they all involve grouping of elements. jsfiddle: https://jsfiddle.net/erama035/p9dagmL3/3/ <div ...

Creating a dynamic form that efficiently captures user information and automatically redirects to the appropriate web page

Sorry for the unusual question, but it was the best way I could think of asking. I have come across websites with fill-in-the-blank lines where you can input your desired information and then get redirected to another page. For example: "What are you sea ...

Tabulator filter - Enhancing CSS elements for a unique touch

Is there a way to customize the CSS elements of filters used in tabulator.js? Specifically, I am looking to: Apply different background colors to text filters Add a down arrow on the right side of each drop-down filter box I have included a screenshot ...

What is the best way to utilize nav and main-nav in CSS?

Working with HTML and CSS <nav class="nav main-nav"> </nav> Styling with CSS main-nav li{ Padding:0 5% } I am a beginner in HTML and CSS and facing an issue. I noticed that when using main-nav in CSS, I'm not getting the de ...

Utilize the power of Facebook login in your Parse client side application by integrating it with the user object

Currently, I am in the process of implementing a login system using both the Parse and Facebook Javascript SDK. While I have successfully implemented authentication on the client side, I am now facing the challenge of accessing the user object (generated ...

Guide on implementing various styles for a class in Tailwind CSS when transitioning to dark mode with the help of Next.js 13.4 and next-theme

Is it possible to apply unique styles for a class in Tailwind CSS when transitioning to dark mode using Next.js 13.4 and next-theme? I am currently setting up a dark theme in Tailwind CSS with Next.js 13.4 utilizing next-theme. Within my globals.css file, ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...