Display One Div at a Time in Sequence on Page Load Using jQuery

I have come across this question multiple times:

How to Fade In images on page load using JavaScript one after the other?

Fade in divs sequentially

Using jQuery .fadeIn() on page load?

Despite trying various recommended methods, I'm still unable to achieve the desired outcome. My goal is to display three lines of text (each wrapped in a div) sequentially when the page loads. Here is my current code:

HTML:

<div class="row"><!--second row-->
<div class="col-lg-12 center">
    <div id="tagline-wrapper">
        <div class="center-text hidden1">Responsive</div>
        <div class="between-lines">
            <div class="line"></div>
            <div class="clean hidden2">Clean</div>
            <div class="line"></div>
        </div>
        <div class="center-text hidden3">Powerful</div>
    </div>
</div>
</div><!--end row-->

CSS:

.center {
 text-align: center;
 display: flex;
 color: #ffffff;
 font-family: 'proxima_nova_ltsemibold';
 text-transform: uppercase;
 font-size: 52px;
}

#tagline-wrapper {
margin-top: 150px;
margin-left: auto;
margin-right: auto;
}

.center-text {
text-align: center;
font-family: 'proxima_nova_ltsemibold';
font-size: 52px;
text-transform: uppercase;
color: #ffffff;
}

.between-lines {
display: flex;
align-items: center;
}

.line {
border-bottom: 2px solid #ffffff;
display: block;
flex-grow: 1;
height: 0;
}

.clean {
padding: 0 1.5rem;
text-align: center;
font-family: 'proxima_nova_ltsemibold';
font-size: 52px;
text-transform: uppercase;
color: #ffffff;
}

/*initially hide elements*/

.hidden1 {
display: none;
}

.hidden2 {
display: none;
}

.hidden3 {
display: none;
}

JavaScript

 $(document).ready(function(){
 var elements = [ '.hidden1', '.hidden2',' .hidden3' ];

  for (var i = 0; i < elements.length; i++) {
  setTimeout(function() {
      $(elements[i]).css('opacity', '1');
      }, 1250 * i);
  }

  });

The above JavaScript approach was suggested in the initial linked article.

JSFiddle attempts with different techniques can be found here: 1. Attempt 1
2. Attempt 2
3. Attempt 3

Thank you.

Answer №1

There are a few key issues that need to be addressed and documented:

1. The scope of for loops in JavaScript can be tricky, especially when dealing with closures inside loops. You can find more information about this here. In your case, using i in a setTimeout function may lead to unexpected behavior due to the global declaration of i.

2. Modifying the opacity of hidden elements is ineffective if their original state is display: none;. To make them visible, change the CSS property to opacity: 0; and consider adding a transition effect like transition: opacity 1s; for a smooth fade-in animation.

3. Your array structure is incorrect. Each item should be enclosed in quotes and separated by commas, whereas your current format is a single string with commas inside it.

var elements = ['hidden1', 'hidden2', 'hidden3'];

4. Trying to access the .style property on strings stored in the elements array will result in an error since they are not HTML elements. Ensure you select the elements before applying styles to them.

To address these issues, consider implementing the following solution along with explanations provided within the JavaScript code comments:

var elements = ['hidden1', 'hidden2', 'hidden3'];

for (let i = 0; i < elements.length; i++) {
  var thisElement = $("." + elements[i]); 
  fadeInElement(thisElement, i);          
}

function fadeInElement(elem, time) {      
  setTimeout(function() {
    elem.css("opacity", "1");             
  }, 1250 * time);                        
}
body {
  background-color: black;
}

.center {
  text-align: center;
  display: flex;
  color: #ffffff;
  font-family: 'proxima_nova_ltsemibold';
  text-transform: uppercase;
  font-size: 52px;
}

#tagline-wrapper {
  margin-top: 150px;
  margin-left: auto;
  margin-right: auto;
}

.center-text {
  text-align: center;
  font-family: 'proxima_nova_ltsemibold';
  font-size: 52px;
  text-transform: uppercase;
  color: #ffffff;
}

.between-lines {
  display: flex;
  align-items: center;
}

.line {
  border-bottom: 2px solid #ffffff;
  display: block;
  flex-grow: 1;
  height: 0;
}

.clean {
  padding: 0 1.5rem;
  text-align: center;
  font-family: 'proxima_nova_ltsemibold';
  font-size: 52px;
  text-transform: uppercase;
  color: #ffffff;
}


/*hide elements initially*/

.hidden1, .hidden2, .hidden3 {
  opacity: 0;
  transition: opacity 1s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <!--second row-->
  <div class="col-lg-12 center">
    <div id="tagline-wrapper">
      <div class="center-text hidden1">Responsive</div>
      <div class="between-lines">
        <div class="line"></div>
        <div class="clean hidden2">Clean</div>
        <div class="line"></div>
      </div>
      <div class="center-text hidden3">Powerful</div>
    </div>
  </div>
</div>
<!--end row-->

Answer №2

Here is my unique solution to help you with your issue:)

$(window).load(function() {
  var $word1 = $(".word1");
  var $word2 = $(".word2");
  var $word3 = $(".word3");

  $word1.fadeIn(1000, function() {
    $word2.fadeIn(1000, function() {
      $word3.fadeIn(1000);
    });
  });
});
.word {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="word word1">
  this
</div>

<div class="word word2">
  is
</div>

<div class="word word3">
  working
</div>

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

React Scheduler by Bryntum

After successfully discovering some functions related to various actions, I find myself still in need of additional functions: Currently, I am utilizing these functions by passing them directly as props to the Scheduler React Component: - onBeforeEventSa ...

Should I specify each protected route in the middleware file in the matcher for NextJs 14?

Below is the middleware file I've implemented: import { NextResponse } from "next/server"; import { NextRequest } from "next/server"; import { getApiAuth } from "./app/middleware/api/auth"; const validateApi = (req: Requ ...

The order in which JavaScript files are loaded is critical, especially when dealing with external

After experiencing issues with my script not working because it was loaded before jQuery by the client (a necessity), I am seeking a solution. My challenge lies in ensuring that my code waits for jQuery to load before execution, especially when dealing wi ...

Creating grids and dividing them using a combination of CSS, JavaScript, and PHP

I've encountered an interesting challenge while working on a web project and would love some advice on how to tackle it: Within a database, I have a collection of images that I want to display in a grid format. The twist is that higher ranked images ...

Using Unobtrusive Ajax, learn to integrate data-ajax-confirm with sweetalert

Here is an example of a form using AJAX: <form method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-confirm="Are you sure you want ...

How to insert a row above the header in an Excel sheet using JavaScript within

i am using excel js to export json data to excel. The json data is successfully exported to the sheet, but now I need to add a row that provides details of the sheet above the header text. for more details please refer image the code is shown below: i ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...

The scale configuration for scale: x is not valid for creating a time scale chart using chart.js

I am currently utilizing VueJS and attempting to integrate a time scale chart using Chart.js. However, I encountered the following error: Invalid scale configuration for scale: x Below is my configuration : First, I have a component named Chart.vue with ...

The request parameter is missing when trying to invoke methods on the MultiActionController

During the Spring 3.0 era suppose I have a jsp page with two different links, each calling a different method on MultiActionController <form:form method="POST"> <a href="user.htm?action=add" style="color: blue;">Add</a> <a hr ...

Issue resolved: Mysterious fix found for background images not displaying in NextJS React components

I am having trouble displaying a background image on an element in NextJs using Typescript and Tailwind. I do not believe it is a TypeScript issue since I am not receiving any errors or IntelliSense warnings. Below is the code I am working with: var classn ...

Adjusting the size of all elements on a webpage

Upon completing my project, I noticed that my localhost:3000 is zoomed in at 125%, causing it to appear less than ideal at 100% zoom. Is there a way to adjust the zoom/scale of my website to match how it appeared on my localhost environment? I came across ...

Adjust the spacing of a div based on the fluctuating height of another dynamically changing div

Is it possible to dynamically adjust the margin of a div using jQuery or JS? Currently, I have set a margin on a div by calculating the height of a container that includes images. var articleImageHeight = $('.slides_control').height(); $(' ...

By clicking anywhere, AngularJS will remove the specified class

Imagine having a search box that is displayed after the user clicks on a button. Great so far, right? But what if you want to add another feature - making the search box disappear when the user clicks anywhere else. How can this be achieved with AngularJS? ...

Integrate a fresh component and include a hyperlink to the URL simultaneously

Seeking to create a system where clicking an item in the navbar loads a new component on the screen, I am faced with the challenge of maintaining state while also updating the URL. Allow me to provide more details: Below is my current navbar code snippet: ...

Exporting a object in Angular2 Using TypeScript

I've been working on a small Angular2 application using Typescript and things have been going smoothly so far. My goal is to utilize a file called config that contains all the necessary settings for the application. Here's the file in question: ...

Converting data from Node.js 6.10 from hexadecimal to base64 and then to UTF-8

I have a code snippet that generates "data" containing a JSON object. My goal is to extract the HEX-value from the Buffer in the data, and then decode it from HEX to BASE64 to UTF8 in order to convert it into a string. Here is the code snippet: console.l ...

PushSharp powering the cutting-edge HTML5 mobile app

I am currently following an article that covers the process of configuring and sending Apple Push Notifications using PushSharp. We have successfully completed steps 1 to 20. However, I am facing issues with step 21 and step 22 of the mentioned article as ...

PHP regular expression /only match 10 whole digits/;

Currently, I am working on updating a PHP script that contains the following code snippet: function CheckNumber(MyNumber) { var MN = /^\d{10}$/; if (MN.test(MyNumber)) { return true; } return false; } The current script enfor ...

What is the process for retrieving DOM elements and JavaScript variables using PHP?

I am currently developing a PHP script that will dynamically generate tables in MySQL based on the user's input for the number of columns and column names. However, I have encountered some challenges when trying to access DOM elements and JavaScript v ...

Exploring the implementation of toggling functionality for nested children within <li> elements using jQuery

Unable to get the toggle function working on child nodes. Can someone assist me with this issue? $(document).ready(function() { $('label.tree-toggler').click(function() { $(this).parent().children('ul.tree').toggle(300); }); ...