Animation displayed on page load before running

Is there a way to ensure that my animation runs smoothly without any lag or jankiness, either while the page is loading or immediately after loading?

I have attempted to preload the images using a preload tag in the header of my HTML, but unfortunately, that did not solve the issue.

The animation consists of three images that initially have no width, height, or opacity. They gradually expand and become visible when the corresponding text-option is clicked, creating the effect of the image growing from either the left or right side of the container.

Upon loading the page, the first image (the one with the active class) is displayed and fully loaded. However, when a different text option is clicked, the image expands very slowly. Once the image is fully loaded, it does not experience this slow expansion issue again until the next refresh. I attempted to preload the image using the

<link rel="preload" href="img.png" as="image">
tag, but it had no effect.

For a visual demonstration of the problem, you can view this video: Video

document.addEventListener("DOMContentLoaded", function() {
  const textOption = document.querySelectorAll(".text-option");
  const selectableImage = document.querySelectorAll(".selectable-image");

  function clickedTextOption(clickedOption) {
    textOption.forEach((option, index) => {
      const active = option.classList.toggle("active", option === clickedOption);
      selectableImage[index].classList.toggle('active', active);
    });
  }

  textOption.forEach(option => {
    option.addEventListener("click", () => {
      clickedTextOption(option);
    });
  });
});
.section-2 {
  display: flex;
  background-color: var(--second-background);
  padding: min(100px, 3svw);
  box-sizing: border-box;
  height: 60vh;
}

.section-2 .image-container {
  width: 50svw;
  height: 100%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
}

.section-2 .image-container img {
  width: 0%;
  opacity: 0;
  transition: all 0.5s ease;
}

.section-2 .image-container .selectable-image.active {
  opacity: 1;
  width: 100%;
}

.section-2 .text-selection-container {
  width: 50%;
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  padding: min(50px, 2svw);
  padding-left: 0;
}

.section-2 .text-selection-container .text-option {
  margin: 1svw;
  padding-left: min(50px, 2svw);
}

.section-2 .text-selection-container .text-option .title {
  font-size: 2svw;
  margin-bottom: 0.5svw;
  font-weight: 700;
}

.section-2 .text-selection-container .text-option .description {
  font-size: 1svw;
  font-weight: 400;
}

.section-2 .text-selection-container .text-option.active {
  border-left: 4px solid var(--primary);
  padding-left: calc(min(50px, 2svw) - 4px)
}
<section class="section-2">
  <div class="image-container">
    <img src="img.png" alt="" class="selectable-image active">
    <img src="img.png" alt="" class="selectable-image">
    <img src="img.png" alt="" class="selectable-image">
  </div>
  <div class="text-selection-container">
    <div class="text-option active">
      <p class="title">Title</p>
      <p class="description">Description</p>
    </div>
    <div class="text-option">
      <p class="title">Title</p>
      <p class="description">Description</p>
    </div>
    <div class="text-option">
      <p class="title">Title</p>
      <p class="description">Description</p>
    </div>
  </div>
</section>

P.S. img.png is just a placeholder

What is the most effective way to prevent this initial lag when loading the animation?

Thank you in advance!

Answer №1

At the end of it all, I found myself effortlessly cycling through the entire animation upon page load. The first active image was cleverly added as a cover image to conceal it from any swift scrollers:

<div class="cover-image"></div>
<img src="img.png" alt="" class="selectable-image active">
<img src="img.png" alt="" class="selectable-image">
<img src="img.png" alt="" class="selectable-image">

The CSS magic:

    .cover-image {
      background: url(img.png) center/cover;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      z-index: 1;
      opacity: 0;
    }
    
    .cover-image.visible {
      opacity: 1;
    }
    .selectable-image {
      width: 0%;
      opacity: 0;
      transition: all 0.5s ease;
    }
    .selectable-image.active {
      opacity: 1 !important;
      width: 100% !important;
    }
    .selectable-image.auto-active {
      opacity: 1 !important;
      width: 100% !important;
    }

Behold, the JS sorcery:

function setStyles() {
    selectableImage.forEach((imgNum, index) => {
      setTimeout(function () {
        imgNum.classList.add("auto-active");
        console.log("completed" + imgNum);

        // Say goodbye to the "auto-active" class after 0.5 seconds
        setTimeout(function () {
          imgNum.classList.remove("auto-active");
        }, 500);
      }, 500 * index);
    });

    coverImage.classList.add("visible");

    setTimeout(function () {
      coverImage.classList.remove("visible");
    }, 700 * selectableImage.length);

    console.log("ended");
  }

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

Incorporating photos within the layout of a Twitter Bootstrap grid

Looking to showcase images like the ones found here: https://i.stack.imgur.com/eD4GD.jpg These images are original and come in various sizes. I want a hover effect that includes blur, fogging effects, and text placed in the middle of the picture. Check ou ...

Is there a way to verify the textbox value in MVC without the need for clicking submit or performing a postback

Exploring MVC for the first time. I am working on a Registration Form with 10 textboxes for id, name, address, etc. I need to validate if the entered Id is already in the database and display the status without requiring the user to click a submit button. ...

Inject CSS values dynamically

I am currently working on dynamically setting the color of a div. To provide some context, let's examine the following: <!doctype html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div clas ...

Encountering issues with loading Angular formControl

I've been going through an Angular tutorial on forms, which you can check out here. In my 'datasources.component.html' file, I have the following code: <form [formGroup]="queryForm"> <label>Query: <input type="text" formCont ...

Can you identify the language of this HTML include code snippet?

Recently, I came across some .html files that include tags in a different format: [% INCLUDE '/path/to/footer.html' %] This bracket-and-percent-sign tag is unfamiliar to me. Does anyone know what it is used for? ...

How Keyof can render an object undefined and prevent accurate verification

Encountering TS2532 error: Object is possibly 'undefined' while attempting to access an object's value by dynamically selecting the key. TypeScript seems to be restricting me from checking the field values, and I'm unsure of the underly ...

Send the JSON output of a MySQL query as an argument to my EJS template in a Node.js/Express application

I've been using res.json(rows) to display my users on the screen, but now I want to pass the object obtained from the query to an ejs file for display. However, when I try to do this as shown in my code below, the passed object becomes a string and I& ...

What is the best way to enhance an object using a class in ES6?

In an effort to improve the clarity of my ES6 class definition, my current code looks like this: class SomeClass { constructor({a, b, c, d, e}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; // additional code here ...

Indexing text fields for MongoDB collection that have been populated

Currently, I am in the process of learning how to use indexing with Mongoose/MongoDB and I am facing an issue that I can't seem to resolve. This is the schema I am working with: const timeSchema = new mongoose.Schema({ actionId:{ type:St ...

Jquery countdown that persists even after refreshing the page with F5

Currently, I am in search of a jquery plugin for a countdown feature that will retain the timer even if the page is refreshed. I am developing an application for a questionnaire and I would like to display a countdown timer set to 60 minutes. In my applica ...

How to apply styling to a specific portion of text within a list element using Vue.js

Despite my best efforts, I am struggling to style only the word "healthy" within the 'It is healthy!' string using computed properties, watchers, and methods in vuejs. I'm at a loss for how to achieve this unique styling. <template> ...

What are the steps to ensure a form does not trigger the action URL and instead only prints the data upon submission

Currently, I am working on creating a form that will submit without opening the action URL when a button is clicked. Additionally, after submission, I want to display a message and clear the form. Can anyone guide me on how to achieve this? <form id="c ...

Unable to locate _app.js file in nextJs

Currently, I am utilizing npx create-next-app for generating my NextJs project and now I am looking to incorporate global styles using bootstrap Upon downloading bootstrap, the suggestion was to add global styles in pages/_app.js, but I couldn't loca ...

What is the best way to align text in the center of a div?

I just created this dropdown menu, but I am encountering an issue. Whenever I resize the div or h4 element, the text ends up at the top. Even after trying to solve it with text-align: center;, the problem persists. Here is a visual representation of what ...

Add the value of JQuery to an input field rather than a select option

Is there a way to append a value to an input field using JQuery, instead of appending it to a select option? Select option: <select name="c_email" class="form-control" ></select> JQuery value append: $('select[name=&q ...

Refresh data with Axios using the PUT method

I have a query regarding the use of the HTTP PUT method with Axios. I am developing a task scheduling application using React, Express, and MySQL. My goal is to implement the functionality to update task data. Currently, my project displays a modal window ...

Retrieve all elements from JSON using jQuery

JavaScript: function loadDoc(url) { $.ajax({ url: 'mytestjson', dataType: 'json', cache: false }).success(function (result) { console.log(result); //var txt = result.newBranches[0].newNon ...

Unexpected token error occurs when making cross-domain AJAX requests to the server and receiving a JSON object

I have set up an express server to handle get requests to specific url endpoints. When responding to these requests, I am sending back data in JSON format to enable making Ajax calls and retrieving data from the page. To allow for cross-domain requests, I ...

"Exploring the process of implementing a fixed method POST in Angular 5

When developing an application for Portal, I encountered an issue where a newly created role is not displayed without refreshing the browser. How can I ensure that the added element is directly displayed in the table without needing to refresh the browser? ...

Navigate a JSON object using JavaScript

As I continue to juggle learning code with my job, I am diving into the world of creating charts using AMcharts. My goal is to generate multiple data sets based on orientation and potentially expand further in the future. In the JSON snippet below, you can ...