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

Link inserted in between spaces

Working with Eloqua. Any ideas on what might be causing a space to appear in a link? The space doesn't show up during testing, only in the live version. Here is the code snippet: <p style="line-height:18px;"> <font face="calibri, Arial, H ...

Tips for managing multiple conditional statements in PHP

List item Seeking opinions on the most efficient method to accomplish a task. There are two inputs - email and phone, with JQuery validation applied successfully. The requirement is that both inputs cannot be empty, but it's acceptable if only one is ...

Utilize tag helpers to choose an option within a select element

I am facing a challenge in my ASP.NET Core application where I need to create a specific HTML structure in a Razor view based on a model instance. The HTML code I need to generate is a dropdown list with multiple options, each having custom attributes like ...

step by step guide on populating dropdown options with ajax in spring mvc

I am new to using ajax and spring mvc. I successfully retrieved data from my MongoDB database via an ajax call. Now, I need assistance with setting dropdown values based on the ajax object. home.jsp <select class="form-control" id="list1value"> &l ...

Having trouble accessing listview capabilities in jquerymobile?

I am currently delving into the world of jquerymobile. I am experimenting with a sample project where I aim to showcase a listview. Below is the code that I have been working on. <!doctype html> <html> <head> <link rel="stylesheet" h ...

Determining the Area of a Polygon Based on its Slope or Angle

Is it possible to calculate the area of a polygon when it has an inclination or slope? I have both the angle/slope and the points of the polygon, and I need to determine the area. How can this be achieved? ...

What should we name this particular style of navigation tab menu?

What is the name of this tab menu that includes options for next and previous buttons? Additionally, is there a material-ui component available for it? ...

Ran into a JavaScript heap memory issue while attempting to perform an npm install on Azure pipeline

Currently in the process of updating my angular projects from angular 16 to angular 17. When running npm install, everything runs smoothly with angular 17 on my personal laptop. However, when attempting the same process on Azure pipeline, I encounter an er ...

The CSS layout is not positioning elements correctly

Here is a preview of how I want my final design to appear: I am facing difficulty in properly aligning the two columns using my CSS code. Whenever I apply the float: left; property, the columns end up stacking on top of each other. /*------ Code st ...

Filtering objects in JavaScript using a technique similar to list comprehension

I'm dealing with a basic array structure that resembles: obj = {1:false, 2:true, 3:true} My goal is to extract an array containing all the keys in the object that have a value of true. In Python, you can achieve this easily using: >>> [ke ...

How can I retrieve the array data that was sent as a Promise?

I have a database backend connected to mongoDB using mongoose. There is a controller that sends user data in a specific format: const db = require("../../auth/models"); const User = db.user const addProduct = (req, res) => { User.findOne({ ...

Establishing a client cookie will help deter any attempts at re-registering

Due to the inability to run server-side code, I am limited in implementing a PHP session for a registration form. Instead, I have opted to utilize a client cookie to ensure that each person can only register once with a unique email address. After reading ...

I encountered an issue with Array map when attempting to access the data during a dynamic rendering process

function UserTransactionsComponent1() { const [accounts, setAccounts] = useState(); useEffect(() => { async function fetchData() { const res = await fetch( 'https://proton.api.atomicassets.io/atomicassets/v1/accounts' ...

How to use jQuery to autoplay audio without user interaction

In the process of creating a dashboard that provides sound notifications for new orders to users, I encountered an issue where the audio playback would fail due to lack of user interaction with the document. Despite trying solutions found in various posts, ...

Mobile device causing issues with sticky footer functionality

Can anyone help me troubleshoot an issue with my sticky/floating bottom footer on a calorie calculator? It works fine on desktop but not on mobile. Any ideas what might be causing the problem? HTML: <footer class="footer"> <div class="summar ...

Issues arising from jQuery AJAX request in Chrome extension

BLUF: The AJAX call from my Chrome extension is not functioning properly. AJAX: $.ajax({ type: "GET", url: "http://weather.aero/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&stationString=KFBG&hour ...

Generating a dynamic clickable div using Angular 6

How can I create a user-friendly interface that displays an image with clickable divs around detected faces, allowing users to view specific attributes for each face? I'm looking for a solution where I can have divs or buttons around each face that t ...

Utilizing chart.js data source plugin in React application (react2chartjs)

Upon receiving inspiration from a question regarding importing data from Excel and presenting it as charts using ChartJs (Import data from Excel and use in Chart.js), I was able to successfully achieve this goal. However, my attempt to replicate this proce ...

Iterating through the Bootstrap grid

https://i.sstatic.net/XMIzT.jpg I'm attempting to create a layout similar to the image provided. Currently, I am utilizing WordPress and WooCommerce and aiming to showcase products in this manner. The following HTML code is what I have been working ...

Utilizing Host Styles in Angular2 Components

In the midst of developing a custom form component for my Angular project, I am facing challenges with styling. I wish to allow variable widths for the input element and have them controlled by the host component. For instance: <my-input class="input" ...