Switching between different sections of a webpage

Seeking assistance with implementing a transition effect between sections on a single-page application. All sections are located on the same page, but only one section is displayed at a time. When an event occurs, the display property of the requested section is toggled to appear. I want to introduce a delay in displaying the incoming section, like after 5 seconds, rather than it appearing immediately. How can I achieve this? I have tried using setTimeout but it doesn't seem to work as expected. Here is an overview of the problem:

  1. All sections except one have display set to none.

  2. An event triggers the display of the requested section and toggles the display property of other sections.

  3. Upon a section request, there should be a transition or timeout before the section is displayed. HTML code snippet is provided below.

HTML

<div class="main-container">
       <div class="page padding main" id="page-main">
         <!-- Content of the main page -->
       </div>
       <div class="page u-none" id="page-login">
         <!-- Login page content -->
       </div>
       <div class="page u-none" id="page-signup">
         <!-- Signup page content -->
       </div>
       <div class="page u-none" id="page-dashboard">
         <!-- Dashboard page content -->
       </div>
     </div>

CSS

nav {
      display: flex;
    }
    /* Utility classes */
    .u-none {
      display: none;
      opacity: 0;
      animation: 2s fadeIn forwards;
    }

@keyframes fadeIn {
  100% {
    opacity: 1;
    display: block;
  }
}

Javascript

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) => {
    setTimeout(() => {
      if (EL.id === id) {
        EL.classList.remove('u-none');
      } else {
        EL.classList.add('u-none');
      }
    }, 5000); // Adjust the delay here (in milliseconds)
  });
};

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

Answer №1

I managed to solve this issue by implementing a timer on the add and remove class style, aligning perfectly with my desired outcome. Check out the modified code snippet below:

const switchPage = (id) => {
  pagesList.forEach((page, index) => {
    console.log(`${index} : ${page.id}`);
    console.log(id);
    
    if (page.id === id) {
      setTimeout(() => {
        page.classList.remove('hidden');
      }, 2000);
    } else {
      setTimeout(() => {
        page.classList.add('hidden');
      }, 2000);
    }
  });
};

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

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...

Altering various HTML components with every swipe of SwiperJS

I am new to working with JavaScript and I have integrated a Swiper JS element into my HTML page. Here is the current code I am using: <head> <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css&quo ...

Querying the jQuery-Plugin to interact with AngularJS service methods

How to incorporate a JavaScript file into multiple Jquery plugins for accessing functions from JavaScript startTransactionController.js var app = angular.module('myApp'); app.controller('startTransactionCtrl', [ '$scope', ...

What makes Nuxt/auth so highly secure?

Picture this scenario: a visitor lands on your Nuxt.js website's homepage. They proceed to authenticate themselves using @nuxtjs/auth-next. After successfully logging in, they gain access to a protected page meant exclusively for authenticated users. ...

Utilizing jQuery's .slidedown alongside Prototype's .PeriodicalUpdater: A Comprehensive Guide

I am currently working on creating an activity stream that automatically updates with the latest entries from a database table every time a new row is added. Right now, I am using Prototype's Ajax.PeriodicalUpdater to continuously check for new entri ...

Missing RequestVerificationToken value when hiding HTML element using jQuery

I am encountering an issue with my ASP.NET MVC 4 form that involves checkboxes being used to show and hide certain HTML elements. When I initially visit the form page, the RequestVerificationToken value is correctly created as a hidden field. Some HTML ele ...

Is it possible to apply a PNG icon collection using CSS?

Throughout various examples, jQuery plugins, and CSS-styled HTMLElements, I have observed the setting of icons on an image with multiple options. I am eager to implement this practice in my own apps. https://i.sstatic.net/WDCH3.png For instance, in the ...

"Learn the steps to enable a click-to-select feature for an item, allowing you to drop it in a different location

I've been spending quite some time trying to come up with a solution for my dilemma. The issue arises because I'm not looking to use drag and drop functionality. https://i.stack.imgur.com/Nh1Db.png My goal is to have 3 divs named 1,2,3 as desig ...

Combining Data Structures in Javascript for Visualization in VueJS

Welcome to my first time asking a question. I am currently working on integrating data from two different API endpoints served by a Django Rest Framework backend and displaying it using VueJS on the frontend. The main issue I'm encountering is how t ...

The Tabbed Panel Bug: Incorrect HTML ID Causing Tab Change Issues in Bootstrap

I've been working on a tabbed panel feature for my website. However, I've run into an issue where clicking on the second, third, and other tabs doesn't change the content displayed - it always stays the same. I'm pretty sure I wrote th ...

Craft a Flawlessly Repeating Sound Experience - Online

I'm facing a challenge in creating a flawless loop of an audio file. However, all the methods I've tried so far have resulted in a noticeable gap between the end and the start. Here are the approaches I experimented with: The first approach inv ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

Working with Ruby on Rails by editing a section of embedded Ruby code in a .js.erb file

Currently, I am in the process of developing a single-page website and have successfully implemented ajax loading of templates to insert into the main content section. However, I am encountering difficulties when trying to do this with multiple templates u ...

Unable to authenticate an HTML form using PHP and Apache 2

In my website's footer, there is a form that I am trying to run using a PHP file located at 127.0.0.1/form.php on localhost. I learned that PHP code inside HTML is commented out, and according to the PHP Documentation, the PHP file needs to be run dir ...

What is the process of disabling console log in a Vue template?

Origins of the $log variable: Vue.prototype.$log = console.log Restricted Areas: <template> <!-- Restricted Area 1 --> <div @click="$log"> <!-- Restricted Area 2 --> {{ $log }} <!-- Restricted Area 3 -- ...

Avoid activating the hover effect on an element situated below another element without the use of JavaScript

After reviewing various posts, it seems like the only solution involves using javascript. Is there a way to hover over one element without affecting the style of another element below it, all without relying on javascript? I'm looking for a solution u ...

I'm working on updating a field within a Firestore document using ReactJS

I am encountering an issue while attempting to update a field within a document in Firestore using ReactJS. Interestingly, others have successfully done it without any errors. app.js const app = initializeApp(firebaseConfig); const auth = getAuth(app); co ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

Ways to align list items in the middle of a webpage with CSS

Currently, I am working on a website and looking to create a customized list where the pictures act as clickable links. You can check out the website here. My goal is to have the links adjust to align left based on the browser size, and also have the imag ...

Struggling to retrieve the Object from a JSON file located at a specific URL

Apologies if this comes across as naive, but my venture into javascript and json is just starting. I'm eager to access the JSON object from the twitter API after executing var myjson; $.getJSON('url of the Object', function(data) { ...