Scrolling on a div can be used to create a looping magnification or scaling

Is there a way to create a seamless loop between #box2 and #box using this fiddle? I want them to reveal themselves in a continuous loop with infinite scroll. Each time one box fills the frame, the next one should appear in the distance, repeating indefinitely.

window.addEventListener( 'load', function() {
  var box = document.getElementById('box'),
      docHeight = document.documentElement.offsetHeight;

  window.addEventListener( 'scroll', function() {
        // normalize scroll position as percentage
    var scrolled = window.scrollY / ( docHeight - window.innerHeight ),
        transformValue = 'scale('+(1-scrolled)+')';

    box.style.WebkitTransform = transformValue;
    box.style.MozTransform = transformValue;
    box.style.OTransform = transformValue;
    box.style.transform = transformValue;

  }, false);

  document.getElementById('nav').addEventListener( 'click', function(event) {
    var level = parseInt( event.target.getAttribute('href').slice(1), 10 ),
        // normalize scroll position
        scrollY = ( level / 4 ) * ( docHeight - window.innerHeight );
    // enable transitions
    box.className = 'transitions-enabled';
    // change scroll position
    window.scrollTo( 0, scrollY );
  }, false);

  function transitionEnded(event) {
    // disable transition
    box.className = '';
  }

  box.addEventListener( 'webkitTransitionEnd', transitionEnded, false);
  box.addEventListener( 'transitionend', transitionEnded, false);
  box.addEventListener( 'oTransitionEnd', transitionEnded, false);

}, false);

I'm seeking guidance on the next steps to achieve a smooth loop between the two divs.

Appreciate your help!

Answer №1

Take a look at this code snippet - it may need some refinement, but it's a good starting point for your project.

http://jsfiddle.net/daZmA/520/

var activeBox = 1;
var totalBoxes = 2;
var previousScroll = 0;

window.addEventListener('load', function() {
  var currentBox = document.getElementById('box' + activeBox),
      documentHeight = document.documentElement.offsetHeight;
  
  window.addEventListener('scroll', function() {
  
  var currentBox = document.getElementById('box' + activeBox);
        // convert scroll position to percentage
    var scrolled = window.scrollY / (documentHeight - window.innerHeight),
        transformValue = 'scale(' + (1 - scrolled) + ')';
 
/*It seems like we're transitioning to a new page - hide all boxes temporarily*/
if(scrolled === 1 || scrolled === 0){
        $(".box").hide();
        }

/*Moving to the next box*/
        /*Ensure we don't exceed the total number of boxes*/
        if(scrolled === 1 && previousScroll != 0){
          if(activeBox + 1 <= totalBoxes){
            window.scrollTo(0, 0);
            activeBox++;
          }
        }
        
        /*Moving to the previous box*/
        if(scrolled === 0 && previousScroll != 1){
          if(activeBox - 1 >= 1){
            window.scrollTo(0, documentHeight);
            activeBox--;
          }
        }
        
        /*Show the current active box*/
        $("#box" + activeBox).show()
        
        previousScroll = scrolled;

    currentBox.style.WebkitTransform = transformValue;
    currentBox.style.MozTransform = transformValue;
    currentBox.style.OTransform = transformValue;
    currentBox.style.transform = transformValue;
    
  }, false);
  
  function endTransition(event) {
    // disable transition
    currentBox.className = '';
  }
  
  currentBox.addEventListener('webkitTransitionEnd', endTransition, false);
  currentBox.addEventListener('transitionend', endTransition, false);
  currentBox.addEventListener('oTransitionEnd', endTransition, false);
  
}, false);

Answer №2

Although the code is a bit messy, it gets the job done. It currently only works by scrolling down, but it can easily be adjusted to handle scrolling back up. You may need to set window.scrollY to the middle of the window and proceed from there, monitoring the scroll direction. The transition occurs when the scale is 0.

if(scale == 0){
    outer_container.appendChild(current_box);
    var older_box = current_box;
    current_box = current_box == box ? box2 : box;
    container.appendChild(current_box);
    window.scrollTo(0,0);
    older_box.style.WebkitTransform = "";
    older_box.style.MozTransform = "";
    older_box.style.OTransform = "";
    older_box.style.transform = "";
}

between inner and outer container

<div id="outer-container">
  <div id="container">
    <div id="box"></div>
  </div>
  <div id="box2"></div>
</div>

View example

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

What is the best way to have the text in my table cell wrap when it reaches the width of the image in the same cell?

Within the table, I have <td> elements structured like this: <tr> <td> <p class="tableText">Lengthy random text..........</p> <img src="www.imageurl.com/img.png" width="33vw"> </td> &l ...

Adjusting image sizes in WordPress using CSS and HTML

I am currently working on a blog using the Marlene theme on Wordpress. For my posts, the default image resolution is 835x577, which suits my needs perfectly (see example post). However, I also have a "News" page where I want to display a list of all news ...

Tips for validating a session on a React client following a successful authentication via an Express session

After setting up an express REST API backend and React Front End, the front end app redirects users to the signin page using OAuth. The express server then creates a session ID after successful authentication, which can be seen as a browser cookie connect. ...

The state of my React components keeps disappearing

Within my code, I have implemented a click event on the InterestBox to trigger updates in its appearance and alter the state of its parent container. However, despite inspecting the element using React Developer Tools and attempting API requests, the stat ...

Why does CSS respect height:auto for relative positioned parent elements but not width:auto?

Although CSS position properties may seem simple at first, when building a layout, tons of weird edge cases can come out of nowhere. One thing that I always overlooked was using height: auto or width: auto. To gain a better understanding, I stumbled upon ...

What could be causing a parse error and missing authorization token in an AJAX request?

I recently wrote some code to connect a chat bot to Viber using the REST API. The main part of the code looks like this -: $.ajax({ url : url , dataType : "jsonp", type : 'POST', jsonpCallback: 'fn', headers: { 'X-Viber-Auth- ...

Updating JQuery dropdown menu fills in additional form fields based on selection

I have a dropdown menu (select) that is dynamically generated using JSON data from a PHP script and JQuery. Please refer to the image under the Components label. The select menu displays the Component name and Component ID as values. I would like to use a ...

Excessive text in HTML div element

Whenever I maximize the window in any browser, I type a long string in a div or span tag. It perfectly fits within the div tag. However, when I minimize or compress the browser width, the text spills out of the div area. I am looking for a solution to set ...

Managing the height of a TextArea within a Flexbox environment

After exploring various methods for achieving auto-height in a textarea, I decided to go with the contenteditable approach as it seemed cleaner to me. However, while it worked perfectly on its own, it failed when placed within flexbox containers. I experi ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

Is your AngularJS code throwing an error?

$scope.logout = function () { //var auth_token = $cookieStore.get('auth_token'); Auth.delete({ 'auth_token': $cookieStore.get('auth_token') }, function(data){ $scope.isLoggedIn = false; $cookieSto ...

What is the best way to retrieve the content of a specific class in Selenium WebDriver?

Python Code : from selenium import webdriver from selenium.webdriver.chrome.options import Options options = webdriver.ChromeOptions() options.add_argument(r"--user-data-dir=C:\Users\bji\AppData\Local\Google\Chrome\ ...

The output from the Angular .then function is not showing up on the webpage

Within my stucontrollers.j, I have the following code: /// <reference path="../angular.js" /> var stucontrollers = angular.module("stucontrollers", []); stucontrollers.controller("GetStudentsList", function GetStudentsList($scope, $http) { $ ...

Pairing TMDb genre IDs and their respective names using JavaScript within the Ember.js framework

If you've ever worked with the TMDb (The Movie Database) api for movies, you might have encountered this issue. I am struggling to display the genre names for each movie shown. My goal is to replace the numbers in genre_ids from the movies api with th ...

Bootstrap 3 Menu with Multiple Scrollable Columns

My Bootstrap 3 website has a navbar with two dropdowns. One of the dropdowns can have as few as 4 items or as many as 150. These items are short, only a few characters each. Initially, I created a 3-column dropdown using the solution provided in this answ ...

When examining an element in an Angular application using Chrome Dev Tools, why do I not observe raw HTML code?

Just as the title suggests, my question is: Even if browsers don't understand Angular, why am I able to see Angular elements while inspecting the DOM despite using AOT (Ahead-Of-Time Compilation) which means there is no Angular compiler in the browse ...

Flexbox allows you to easily manage the layout of your website

I am currently working on a CSS project and have encountered an issue. Whenever I apply the "display: flex" property to the .student element, the border around it mysteriously doubles. The reason for wanting to use the flex property is to align the text ve ...

Is it advisable to substitute setTimeout with node-schedule in a node.js environment?

How can I prevent players from entering a raffle between 11:55pm - 11:59pm every Thursday? I attempted to use node-schedule to block access during this time frame by scheduling it to run every second, but unfortunately, I was still able to access the route ...

The view page encounters an issue when attempting to load a null element

I am currently working with a JavaScript function that generates links on my webpage based on the user's selection from a DropDown menu. I have implemented checks for this JavaScript function in two scenarios: when the user selects an option from the ...

Connecting your HTML file to a CSS stylesheet

I'm struggling to connect my "index.html" file with my "stylesheet.css" file. I've tried copying the code from resources like CodeAcademy and w3schools, but nothing seems to be working. I'm currently using Notepad++ as my text editor - could ...