Determine the scale and position adjustments by assessing the pageYOffset

Currently, I am faced with the following dilemma:

I possess an object along with its initial position;

Upon the initiation of page scrolling, my goal is to have this object move downwards towards the center. Once the scroll reaches 100vh (referred to as 'sectionHeight' in the provided example), the objective is for the object to be positioned perfectly at the screen's center and expand by 1.49 times its original size.

The challenge lies in the mathematical aspect as I am struggling to devise a suitable method for calculating the object's trajectory. Thus far, the code snippet I have developed for adjusting the position consists of somewhat arbitrary values in an attempt to achieve the desired outcome:

if(window.pageYOffset < sectionHeight && window.pageYOffset > 0) {
            productToExpand.style.position = 'absolute';
            productToExpand.style.top = productToExpandPosition.top + window.pageYOffset + 'px';
            productToExpand.style.left = productToExpandPosition.left + window.pageYOffset / 2 + 'px';
        } else if(window.pageYOffset === 0) {
            productToExpand.style.position = 'unset';
        }   else if (window.pageYOffset > sectionHeight) {
            productToExpand.style.top = 1.5 * sectionHeight - productImageToExpand.offsetHeight / 2 + 'px';
            productToExpand.style.left = 'calc(50% -' + ' ' + (productImageToExpand.offsetWidth / 2 + productToExpandPositionLeft) + 'px)';
        }

Furthermore, determining the appropriate formula for resizing the object poses another challenge. Any assistance in addressing these issues would be greatly appreciated.

Answer №1

After thoroughly analyzing your request, I have integrated certain portions of your code while introducing new elements as well. Detailed comments have been provided alongside the modified code for clarity.

    var sectionHeight = vhToPixels(100); // defines the height of a section in pixels
    var sectionWidth = vwToPixels(100); // specifies the width of a section in pixels
    
    var productToExpand = document.getElementById('image1');
    var productToExpandPosition;
    var imgHeight = productToExpand.clientHeight;
    var imgWidth = productToExpand.clientWidth;
    
    var multiplier;
    
    window.onscroll = function() {myFunction()};
    
    function myFunction() {
        if(window.pageYOffset < sectionHeight && window.pageYOffset > 0) {
            productToExpand.style.position = 'absolute';
            productToExpand.style.top =  window.pageYOffset + 'px'; // adjusts position based on scroll
            productToExpand.style.left =  window.pageYOffset / 2 + 'px'; // determines left position
            
            if((window.pageYOffset/500)  < 1) {
                multiplier = 1;
            }
            else {
                multiplier = (window.pageYOffset/500);
            }
            
            productToExpand.style.height = imgHeight * multiplier  + "px"; // sets dynamic height
            productToExpand.style.width = imgWidth * multiplier + "px"; // sets dynamic width
            
        } else if(window.pageYOffset === 0) {
            productToExpand.style.position = 'unset';
            productToExpand.style.height = imgHeight  + "px";
            productToExpand.style.width = imgWidth  + "px";                
        }   else if (window.pageYOffset > sectionHeight) {
            productToExpand.style.top = 1.5 * sectionHeight - productToExpand.offsetHeight / 2 + 'px'; // aligns top position
            productToExpand.style.left = sectionWidth + ' ' + (productToExpand.offsetWidth / 2 ) + 'px)';
            productToExpand.style.height = imgHeight * 1.49 + "px"; // adjusts height
            productToExpand.style.width = imgWidth * 1.49 + "px"; // adjusts width
        }            
        
    }
    
    function vhToPixels (vh) {
        return Math.round(window.innerHeight / (100 / vh)); // converts viewport height to pixels
    }
	
    function vwToPixels (vw) {
        return Math.round(window.innerWidth / (100 / vw)); // converts viewport width to pixels
    }   

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

Loading animation reminiscent of a whirlpool, similar to the movement

In my quest for the perfect animation, I have scoured far and wide. Unfortunately, the one I found at http://jsfiddle.net/pedox/yed68/embedded/result/ is created using css, which many browsers do not yet support fully. I also explored , but found it to be ...

What is the right time to use parentheses when calling functions - and when should you leave them

Currently, I am following along with a tutorial at this link and I've come across some syntax that is confusing to me. The goal is to have "hello" logged to the console every time I scroll. function moveCamera() { console.log("hello"); } document. ...

Tips for aligning an element with another element's position

Is it possible to have the new hello button displayed in exactly the same position as the previous one after clicking the Hello button? const rightDiv = document.querySelector('#rightDiv'); const leftButton = document.querySe ...

Ways to conceal and reveal a different section at the same time (like an accordion)

Looking for guidance on implementing an accordion-style functionality, where clicking a navigation link hides one section and reveals another seamlessly with automatic scrolling to the start of the section (end of the navigation). Any tips or starting poin ...

Dynamic HTML Table with Ajax Click Event Trigger

I have implemented an HTML table that refreshes automatically every 5 seconds and contains some buttons. The issue I am facing is that the event only triggers before the initial refresh. <?php require_once ('UserTableHtm ...

Tips for adding extra spacing between icon and text field using Vuetify

The code snippet below is used for the username section: <v-text-field prepend-icon="fas fa-user" height="60px" placeholder="Username" outlined ></v-text-field> Is there a way to add space between the user ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Async/await is restricted when utilizing serverActions within the Client component in next.js

Attempting to implement an infinite scroll feature in next.js, I am working on invoking my serverAction to load more data by using async/await to handle the API call and retrieve the response. Encountering an issue: "async/await is not yet supported ...

Vue JS Spinner that can be used for multiple components within a single page in the same Vue application

Welcome to my Vue.js app. I am looking to add separate spinners inside each component's body instead of loading for the entire app. If there are any other spinner plugins available, feel free to suggest them. CDN links for Vue.js <script type="te ...

Transforming a numeric value into a 4-byte array using JavaScript

Attempting to write a node server has brought me to the challenge of sending a 32-bit integer to a C# client as the header. The bit shift operators are a bit confusing for me and I am uncertain about how to proceed. It seems that my C# client expects thes ...

Display an Array from a PHP File in HTML Using jQuery

Here is an example of my PHP script used to retrieve and display JSON data: $get_chat = "SELECT * FROM chat WHERE u_id1='$u_id' && u_id2=2 ORDER BY data DESC"; $run_chat = $conn->query($get_chat); if ($run_chat->num_rows > 0) { ...

Embed programming into an iframe upon its loading

I am looking to enhance the functionality of an iframe by injecting HTML and JavaScript code into it upon loading. The goal is to enable users to navigate through different links within the iframe while they are browsing. Here is what I have attempted so ...

Node.js and MySQL are experiencing issues with passport authentication

Attempting to set up login page authentication with passport and MySQL using Node.js isn't going as planned. When accessing the login page in the browser, an unexpected "missing credentials" alert message appears, which isn't defined in the passp ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

Accessing state in a child component through props using "(this.props.(propName))" results in undefined value because of the usage of "This" keyword

Currently, I have a parent component that contains a state with a theme string. This setup is purely for testing purposes, so let's not delve too deep into its practicality at the moment! So far, here is the layout: The Parent Component holds the st ...

The variable $_FILE fails to retrieve the file, resulting in PHP displaying an undefined variable error

I am facing an issue where I am unable to get the image file sent from an HTML form to insert it into a database. The other variables are being posted successfully, as I have checked them by echoing, but the image file is not getting posted. I suspect that ...

I'm having difficulty integrating boostrap with my react application due to issues with the css-loader

In my React index.js file, I am importing Bootstrap and using Webpack 4: import React from 'react'; import ReactDOM from 'react-dom'; import './assets/css/index.css'; import App from './App'; import * as serviceWork ...

Transferring account information to a function call in the near-js-api

I am attempting to utilize the following method in near-js-api for my contract. It requires a Rust AccountId as input. What is the correct procedure to serialize an Account and send it to the contract? Also, are there any specific considerations when inv ...

Make sure to execute a function prior to the ajax beforeSend

Before I upload a file using 'fileuploader', I attempted to check the file first in my beforeSend function: beforeSend: function(item, listEl, parentEl, newInputEl, inputEl) { var file = item.file; let readfile = functio ...

Plugin for managing responses other than 200, 301, or 302 in forms

Currently, I am using the jQuery Form Plugin in my project. Everything works smoothly when the server sends a 200 response as it triggers the success listener seamlessly. However, according to the standard protocol, the browser automatically handles 301 ...