Moving from one page to another

I am attempting to create a transition effect between sections within a single-page application. All the sections are contained on the same page, with only one section displayed at a time while the rest are set to display none. When a specific event is triggered, the display property of the requested section toggles from none to visible. However, I want to implement a delay before the requested section transitions in - for example, a 5-second delay. I have tried using setTimeout but it doesn't seem to be working as expected.

  1. Each section, except one, has display set to none.

  2. An event triggers the display of the requested section and toggles the display setting.

  3. Upon triggering the event, I want to add a delay or transition effect so that the section doesn't appear immediately.

Below is an outline of the problem:

 <!-- Code snippet goes here-->

CSS Styles:

 /* CSS rules go here */

Javascript Code:

// Javascript code goes here

Answer №1

Here is a simple implementation that can be customized for your desired effect. I made some adjustments to your HTML code because the pages were nested, causing them all to hide when the main page was hidden.

const ELS_pages = document.querySelectorAll('.page');
const ELS_buttons = document.querySelectorAll('[data-page]');
const submit = document.querySelector('.submit');

const goToPage = (id) => {
  ELS_pages.forEach((EL, i) => {
    if (EL.id === id) {
      setTimeout(() => {
        EL.classList.remove('u-none');
      
        // THIS TIMEOUT IS IMPORTANT TO ALLOW BROWSER TO REPAINT AFTER CHANGING display PROPERTY. IF NOT, TRANSITION COULD NOT WORK.
        setTimeout(() => {
          EL.style.opacity = 1;
        }, 100);
      }, 1000);
    } else {
      EL.style.opacity = 0;
      
      setTimeout(() => {
        EL.classList.add('u-none');
      }, 1000);
    }
  });
};

ELS_buttons.forEach((EL) =>
  EL.addEventListener('click', () => {
    goToPage(EL.dataset.page);
  })
);

goToPage('page-main');
nav {
    display: flex;
}

nav a {
    color: #00f;
    padding: 5px 10px;
    cursor: pointer;
}

.page {
    opacity: 0;
    transition: opacity 1s ease-in-out;
}

.u-none {
    display: none;
}
<div class="main-container">
    <div class="page padding main u-none" id="page-main">
        <div class="modal hidden">
            <button class="btn-close-modal">&times;</button>
            <h2 class="modal-header">Login to your account</h2>
            <form class="modal-form">
                <div>
                    <label for="input-username">Username:</label>
                    <input id="input-username" type="text"/>
                </div>
                <div>
                    <label for="input-password">Password:</label>
                    <input id="input-password" type="text"/>
                </div>
                <button class="btn header-button">Login &rarr;</button>
            </form>
        </div>
        
        <div class="overlay hidden"></div>
        
        <nav class="header-nav">
            <a href="#" class="header-img">
                <svg viewBox="0 0 256 256" class="header-svg">
                    <path
                            class="path"
                            d="m 15.625507,46.199537 55.767886,-32.030352 55.623047,32.281229 -0.14485,64.311586 0.14485,-64.311586 55.76788,-32.030352 55.62305,32.281229 -0.14485,64.311579 -55.76788,32.03036 -55.62305,-32.28123 55.62305,32.28123 -0.14485,64.31158 -55.76788,32.03035 L 70.958866,207.10393 71.103708,142.79235 126.87159,110.762 71.103708,142.79235 15.480664,110.51112 Z"
                            style="
                   fill: none;
                   stroke: #000;
                   stroke-width: 13;
                   stroke-linejoin: round;
                   stroke-linecap: round;
                 "
                    />
                </svg>
            </a>
            <button
                    class="header-button login"
                    type="button"
                    data-page="page-login"
            >
                LOGIN
            </button>
        </nav>
        
        <div class="header-hero">
            <div class="circle1"></div>
            <div class="circle2"></div>
            <div class="header-text">
                <h1 class="header-text-description">
                    Make Banking Easy with Express
                </h1>
                <p class="header-text-texts">
                    Together we can make banking awesome!
                </p>
                <p class="header-text-texts">
                    Use our mobile app to your need today
                </p>
                <button class="header-button header-buttons" type="button">
                    <a href="">Services</a>
                </button>
            </div>
            <div class="header-image hide-for-desktop">
                <img src="./assets/hand.jpg" alt="" class="header-hand"/>
                <button class="header-image-1">Transfer</button>
                <button class="header-image-2">Loan</button>
            </div>
        </div>
    </div>

    <div class="page u-none" id="page-login">
        <nav>
            <a data-page="page-dashboard">User Settings</a>
            <a data-page="page-main">Logout</a>
        </nav>
        <h1>MAIN PAGE 1</h1>
        <form action="" name="login" method="POST" id="form-1">
            <label for="name-1">Name</label>
            <input type="text" id="name-1" required/>
            <label for="pin-1">Pin</label>
            <input type="text" id="pin-1" required/>
            <button type="submit" class="submit">Submit</button>
        </form>
    </div>

    <div class="page u-none" id="page-signup">
        <nav>
            <a data-page="page-settings">User Settings</a>
            <a data-page="page-login">Logout</a>
        </nav>
        <h1>MAIN PAGE 2</h1>
        <form action="" name="login" method="POST" id="form-id">
            <label for="name-2">Name</label>
            <input type="text" id="name-2" required/>
            <label for="pin-2">Pin</label>
            <input type="text" id="pin-2" required/>
            <button type="submit" class="submit">Submit</button>
        </form>
    </div>

    <div class="page u-none" id="page-dashboard">
        <nav>
            <a data-page="page-main">Back to Main</a>
            <a data-page="page-login">Logout</a>
        </nav>
        <h1>SETTINGS PAGE</h1>
    </div>
</div>

Answer №2

For easy website navigation, consider integrating fullpage.js

This plugin offers a range of customizable settings to suit your needs. You can find more information at https://github.com/alvarotrigo/fullpage.js

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

Encountering an error with Nested MaterialUI Tabs while attempting to open the second level of tabs

I am attempting to create nested horizontal tabs using MaterialUI. This means having a first level of tabs that, when clicked on, opens a second level of tabs. Here is a link to a working example of the code: https://codesandbox.io/s/sweet-pasteur-x4m8z?f ...

Modifying the CSS class of an element does not produce the desired effect after altering its styles using JavaScript

html: <input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/> <br><br><br><br> <button id="s">set to visible class</button> <button id="h"> ...

Redirect in React Route

I've been researching how to programmatically redirect in React, but I'm struggling to get it to work. Here's a simplified version of my code: import React from 'react'; import {render} from 'react-dom'; import {Browser ...

A step-by-step guide on retrieving information from a span and em element with Beautiful Soup

Currently, I am developing a code that is responsible for extracting data from various web pages. # Here's the content of task.py import requests from bs4 import BeautifulSoup url = ('https://www.naukri.com/job-listings-Python-Developer-Cloud-A ...

Updating Jqplot display upon ajax call completion

Currently, I have a Jqplot set up using the AJAX JSON Data Renderer and it's functioning properly. There is a button on the page where users can input new values (updated through ajax) which are then stored in the same DB as the json data source. Whe ...

Creating JSON with PHP: Ensuring consistent keys in JSON output derived from PHP arrays

Is there a method to convert a PHP array (or any other similar PHP object) into JSON while maintaining identical keys for a JSON array? For example: {"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] } It is worth noting that the ...

Sending a JavaScript string to a PHP script from a Chrome extension content script

I am currently developing a chrome extension that is designed to extract text data from specific websites when I visit them, and then store this data in a SQL database. The JavaScript code for data extraction is functioning correctly and is able to capture ...

Tips for creating a dynamic system to continuously add more HTML tables in PHP

I am working with an HTML table where the data is retrieved from a database. I need to add new rows to enter additional data, but the numbering does not continue from the last number. My question is how can I increase the numbering in the table. Please ref ...

Every time I attempt to destructure the state object in react typescript, I encounter the error message stating 'Object is possibly undefined'

Whenever I attempt to destructure my state object in react typescript, I encounter an error stating Object is possibly 'undefined'. When I try using optional chaining, a different error pops up saying const newUser: NewUser | undefined Argument o ...

applying a timeout for the .on(load) event

My goal is to dynamically load images using .on('load') in the script below: .on('load', function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken i ...

Python - Selenium: A guide to locating elements based on color

I have a situation where I need to select only the "Claim" button from the first div, even though both div cases are very similar. Is using background color a good way to identify my element? Or do you have any other ideas? 1. <div class="well well-sm ...

Steps for adding custom text/symbols from a button on the textAngular toolbar

My goal is to include a button on the toolbar that allows users to insert © into the textangular editor (). However, I am struggling to grasp how to add functionality to my registered button. The examples provided by textangular for custom functionali ...

What method is the most effective for preloading images and stylesheets?

One of the main concerns I have is optimizing the load time of my website. I would like to preload images, style sheets, and scripts to ensure a faster loading speed and to prevent users from seeing images loading right before them. Can someone suggest the ...

What is the best way to transform an Object {} into an Array [] of objects with varying structures?

Within my javascript code, I am working with an object structure like this: let obj= { a: { a1: [5,5], a2: [6,6] }, b: { a1: [7,7], a2: [8,8] }, c: { a1: [9,9], a2: [3,3] } } The goal is to ...

What could be causing the discord.js command handler to malfunction?

As I was working on developing a Discord Bot, I encountered an issue with the Command Handler while using a for loop. This is the code in Index.js: client.commands = new Collection(); const commandFiles = fs.readdirSync('./commands').filter(fil ...

Utilizing react js computed property to retrieve a state value: A guide

I recently developed a fading text component where the header fades in and out using transition opacity CSS and a visibility state. To simplify my code, I decided to create a fading text group component that can handle multiple fading texts at once. My goa ...

What are some strategies for sorting information from a list that is constantly changing?

I have been working on a web application built in asp.net that receives data from a web service in JSON format. The current task is to dynamically develop controls for this application. I achieved this by creating a list of labels with stored values using ...

The onclick handler fails to function following the injection of html using jquery AJAX

After using ajax to inject HTML into my page, the onclick handler on a specific part of that injected HTML does not seem to be functioning... Specifically, I am referring to this image... < img class="close_row" src="img/close.gif"/> In jQuery, I ...

Prevent XHR from responding to OPTIONS method

Currently, I am in the process of developing an API that will be hosted on Azure functions and a Web App that will reside on Azure Blob storage. To ensure seamless communication between my API and the users' browsers, I have implemented proper handlin ...

Ways to conditionally display a component in Next.js without the issue of caching CSS styles

I'm a newcomer to Next.js and I'm still trying to wrap my head around how the caching works. Let's take a look at this simplified example: An index page that displays either Test1 or Test2 components, based on whether the current minute is ...