Determine how the scale of a transform changes over time by calculating the function of elapsed time [ transform: scale(x, y

I am currently working on a container that can be expanded and collapsed simply by clicking on a chevron icon. The functionality to collapse or expand the container resides within a function called transformAnimation. This function code closely resembles the example provided in the MDN web docs for requestAnimationFrame. To animate the scaling of the container, I have followed the guidelines outlined in an informative article titled Building performant expand & collapse animations on the Chrome Developers website.

However, I’ve encountered a challenge while trying to calculate the value of yScale, which essentially represents the scaleY() function for the collapse/expand animation based on the elapsed time since the start of the animation.

To further clarify, imagine the container is initially in the expanded state with a yScale value of 6. When the user triggers the toggle button, I expect the yScale value to smoothly decrease from 6 (expanded) to 1 (collapsed) over a specific duration that I control. This behavior mirrors the functionality provided by the CSS property transition-duration: 2s, where the animation duration is adjustable.

Despite my efforts, the current code used to compute the yScale value is not functioning as intended.

// JavaScript code snippets here
// ...
// CSS styles go here
// ...
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="css.css">
</head>

<body>
  <div class="drag-expandable-container">
    <!-- HTML content structure goes here -->
  </div>
</body>
<script type="text/javascript" src="js.js"></script>

</html>

Answer №1

Sharing this as a solution for improved code presentation.

It appears that the task you are attempting to accomplish can be done using Linear Interpolation (abbreviated as "lerp" in the developer community).

You can refer to the following simple function:

function lerp(v0, v1, t) {
    return v0*(1-t)+v1*t
}

This is a basic linear interpolation function that should work well for your calculations. It requires three parameters:

v0, the initial value, e.g., 0
v1, the final value, e.g., 10
t, a value between 0 and 1 representing the progression percentage from v0 to v1

For instance, when you call lerp(0, 10, 0.5), it will return 5, indicating halfway between 0 and 10.

If you were to call lerp(0, 10, 0.9), it would yield 9.

In addition, with t = 0, the function outputs 0, and with t = 1, it gives 10.

Applying this concept to your scenario, you have two container heights:

y0 = height when minimized (0)
y1 = height when maximized (6)

Along with elapsed time (et) and total time (tt) of 2 seconds for opening and closing the container.

We aim to use lerp to obtain the yScale at a specific time t.

While we already know y0 and y1, et cannot directly serve as the t parameter since et ranges from 0 to 2 while t must range from 0 to 1.

To address this, we need to scale et to fit within 0 and 1.

Here's a complete code snippet demonstrating scaling and utilizing lerp:

// Y scale value when minimized
let y0 = 0;
// Y scale value when maximized
let y1 = 6;
// Time taken to transition from 0 to 6
let totalTime = 2000;

// The lerp function
function lerp(v0, v1, t) {
    return v0*(1-t)+v1*t
}

// Simulating the lerp function over time from 0ms to 2000ms
for(let elapsed_time = 0; elapsed_time <= totalTime; elapsed_time += 100)
{
    // Scaling elapsed time to span from 0 to 1 instead of 0 to 2
    let elapsed_time_scaled = elapsed_time / totalTime;
    // Calculating y scale with lerp at the current time
    let scale_y = lerp(y0, y1, elapsed_time_scaled).toFixed(2);

    // Displaying the results
    console.log(elapsed_time, elapsed_time_scaled, scale_y);
}

The output resembles:

0 0 '0.00'
100 0.05 '0.30'
200 0.1 '0.60'
300 0.15 '0.90'
400 0.2 '1.20'
500 0.25 '1.50'
600 0.3 '1.80'
700 0.35 '2.10'
800 0.4 '2.40'
900 0.45 '2.70'
1000 0.5 '3.00'
1100 0.55 '3.30'
1200 0.6 '3.60'
1300 0.65 '3.90'
1400 0.7 '4.20'
1500 0.75 '4.50'
1600 0.8 '4.80'
1700 0.85 '5.10'
1800 0.9 '5.40'
1900 0.95 '5.70'
2000 1 '6.00'

Looks promising! Do you find this helpful?

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

Multiple Ajax calls interacting with each other are causing issues

Within my Index.php file, there is an ajax call that loads a php page containing an HTML form. I am attempting to trigger another ajax call from Index.php whenever a select box is changed. Everything functions properly except for the ajax on change event ...

Validation issue with Reactive Forms not functioning as expected

My latest project involves a user signup component that I created from scratch import { Component } from '@angular/core'; import {UserManagementService} from '../user-management.service'; import {User} from "../user"; import {FormBuild ...

Sections stacked with Bootstrap cards are located beneath a different section

Objective The primary aim is to ensure that all sections display correctly on the mobile version of the website. Challenge An obstacle I am currently facing is: Full width (Looking good) https://i.sstatic.net/EDm3N.jpg Mobile version (Issue) There i ...

This code snippet, document.location.search.replace('?redirect=', '').replace('%2F', ''), is failing to execute properly in Firefox

The functionality of document location search replace redirect to another page works in Chrome, however, document.location.search.replace('?redirect=', '').replace('%2F', ''); it does not work in Firefox; instead, ...

Safari IOS experiencing issue with element disappearing unexpectedly when input is focused

I am facing a situation similar to the one discussed in the question (iOS 8.3 fixed HTML element disappears on input focus), but my problem differs slightly. My chatbox iframe is embedded within a scrollable parent, and when the iframe is activated, it exp ...

Using jQuery .each() within a PHP foreach loop: A guide

In my code, I have a foreach loop that iterates through an array of images, along with some JavaScript logic to add different classes based on whether the width is greater than or less than the height. The issue I'm facing is that the if function onl ...

Stylish Pop-up Box appears hidden behind a different element

Is there a way to fix the issue of the FancyBox plugin being blocked by some part of the HTML on the page when trying to load a Vimeo movie into a popup? Here is the live link: click here : it's when you click on the slider image underneath the yello ...

Does JSON have a special reserved key for identifying the time?

I've noticed an interesting issue when logging the json string of a key labeled tid - it always shows up as 0. Take a look at this example: var transaction = {tid:1, type:0, time:126312736}; var transStr = JSON.stringify(transaction); console.log(tra ...

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

Horizontal rule spans the full width of the content, appearing within an ordered list

Check out this example to see the issue with the horizontal rule not extending all the way across under the number. I've tried using list-style-position:inside;, but that interferes with positioning the number correctly due to the left image being flo ...

Having trouble making z-index work on a child div with absolute positioning

I am attempting to design a ribbon with a triangle div positioned below its parent div named Cart. <div class="rectangle"> <ul class="dropdown-menu font_Size_12" role="menu" aria-labelledby="menu1" style="min-width: 100px; z-index: 0"> & ...

Is it truly unsemantic to use transparent <hr> elements for responsive vertical spacing?

I've recently adopted a unique technique for managing vertical spacing in front-end design by using transparent <hr> elements as spacers. I understand that this method is not favored among most of the web community, but I believe it has its meri ...

How to securely upload and generate a permanent link for the contents of a zip file using express js

I am new to Javascript and Node JS. I have a challenge of uploading a zip file containing only pictures and creating permanent links for these pictures. Currently, I can upload a zip file and extract its contents using the following code snippet: var expr ...

What is the best way to set up a loop for displaying Chat Bubbles?

Is there a way to create a loop for chat bubbles? I want them to appear on the right when I send a message and on the left when the chat partner replies. How can I implement this loop? This is the code I currently have: <div class="Webview"> &l ...

Make sure to concentrate on the input field when the DIV element is clicked

In my React project, I am working on focusing on an input element when specific buttons or elements are clicked. It is important for me to be able to switch focus multiple times after rendering. For instance, if a name button is clicked, the input box for ...

Saving information in binary format to a file

I have a script for setting up an installation. This specific script is designed to access a website where users can input values and upload a certificate for HTTPS. However, the outcome seems to be different from the expected input file. Below is the cod ...

Material UI button component does not have the applied class

I'm encountering an issue with applying a CSS class (redirectButton) to a Material UI button. Despite my efforts, the class is not being successfully applied. Below is the HTML code in question: {(isDataAdapterAdmin && !dataSources?.length) & ...

When is it necessary to use JSON.parse(JSON.stringify()) with a Buffer object?

I am currently working with Buffer objects in my existing code. let dataObject = JSON.parse(JSON.stringify(data)); At first glance, it seems like the above code is redundant and doesn't achieve much. However, replacing it with: let dataObject = data; ...

PHP incorporate diverse files from various subfolders located within the main directory

My question is similar to PHP include file strategy needed. I have the following folder structure: /root/pages.php /root/articles/pages.php /root/includes/include_files.php /root/img/images.jpg All pages in the "/root" and "/root/art ...

The attempt to remove the ajax-loaded page while preserving the original div is proving to be

I have a function that is triggered when a link is clicked. This function uses ajax to load a new page over a div. <pre><code> function displayContent(id) { loadPage_signup = "register.php"; loadPage_info = "userinfo.php"; $.aj ...