Text that fades in and out based on scrolling past a specific point

There's a text containing <p> and <h1>. The text finishes with one <h1>. I'm looking to speed up the Y translation of the <p> twice when I reach the bottom of the document (where the last h1 is located in the middle of the page), while keeping the h1 centered on its own. However, I want the <p> to scroll back up if I scroll back.

Is there an easy way to achieve this using jQuery? I've tried numerous solutions found online, but none have been satisfactory.

$(window).scroll(function(){

    var wScroll = $(document).scrollTop();
    var b = $(document).height() - $(window).height();
    var c = ($(document).height() - wScroll - $(window).height()) * 2;
    var fade = 1 + c / 100;
    var trigger = $('#last').offset().top - $(window).height() / 2;


    if(wScroll > b) {
      $(window).on('scroll', function() {
        $('p').css({
          'transform' : 'translateY('+ c +'px)',
          'opacity' : ''+ fade +''.
        })
      })

    }

});
p, h1 {
  font-family: Baskerville;
  margin: auto;
  max-width: 650px;
  color: #333;
}

p {
  font-size: 21px;
  line-height: 33px;
  max-width: 650px;
  margin-top: 30px;
}

p:nth-child(2):first-letter {
  font-family: Arial;
  font-weight: 700;
  float: left;
  font-size: 72px;
  line-height: 63px;
  padding-right: 12px;
}

h1 {
  font-size: 47px;
  margin-top: 30px;
}

h1:last-child {
  margin-bottom: 0px;
}

.container {
  margin-top: 5%;
  margin-bottom: 50vh;
}
    <div class="container">
    <h1>Hello!</h1>

    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam ornare dictum ligula. Maecenas elementum suscipit nisl. Cras imperdiet leo ac felis dictum luctus. Pellentesque odio nisi, accumsan nec, scelerisque sed, consectetuer nec, justo. Sed tortor sapien, suscipit id, pulvinar vel, elementum id, lorem. Nullam consectetuer risus sit amet nibh. Vestibulum consectetuer, quam vitae euismod volutpat, magna magna consectetuer dui, et accumsan magna dui non nibh. Morbi adipiscing consequat erat. Vivamus quis massa eget orci fermentum laoreet. Morbi posuere purus. Duis feugiat lacus vel nisi. Aliquam ipsum felis, pretium sed, vehicula vel, dictum eget, nibh. Morbi turpis nulla, luctus viverra, pretium in, suscipit vitae, purus.</p>

    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam ornare dictum ligula. Maecenas elementum suscipit nisl. Cras imperdiet leo ac felis dictum luctus. Pellentesque odio nisi, accumsan nec, scelerisque sed, consectetuer nec, justo. Sed tortor sapien, suscipit id, pulvinar vel, elementum id, lorem. Nullam consectetuer risus sit amet nibh. Vestibulum consectetuer, quam vitae euismod volutpat, magna magna consectetuer dui, et accumsan magna dui non nibh. Morbi adipiscing consequat erat. Vivamus quis massa eget orci fermentum laoreet. Morbi posuere purus. Duis feugiat lacus vel nisi. Aliquam ipsum felis, pretium sed, vehicula vel, dictum eget, nibh. Morbi turpis nulla, luctus viverra, pretium in, suscipit vitae, purus.</p>

    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam ornare dictum ligula. Maecenas elementum suscipit nisl. Cras imperdiet leo ac felis dictum luctus. Pellentesque odio nisi, accumsan nec, scelerisque sed, consectetuer nec, justo. Sed tortor sapien, suscipit id, pulvinar vel, elementum id, lorem. Nullam consectetuer risus sit amet nibh. Vestibulum consectetuer, quam vitae euismod volutpat, magna magna consectetuer dui, et accumsan magna dui non nibh. Morbi adipiscing consequat erat. Vivamus quis massa eget orci fermentum laoreet. Morbi posuere purus. Duis feugiat lacus vel nisi. Aliquam ipsum felis, pretium sed, vehicula vel, dictum eget, nibh. Morbi turpis nulla, luctus viverra, pretium in, suscipit vitae, purus.</p>

    <h1 id="last">See ya!</h1>
    </div>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Answer №1

Welcome to the first step in this journey. If there are better ways to achieve this, feel free to share!

$(window).scroll(function(){

// Variables for last paragraph

  var wScroll = $(this).scrollTop();
  var bottom = ($(document).height() - wScroll - $(window).height()) / 2 ;
  var fade = bottom / 100;


  // Implementing fading & scroll effect twice for the last paragraph

  if(wScroll > $('#last').offset().top - $(window).height()){

    var offset = wScroll - $('h1#last').offset().top + $(window).height();

    // Applying transformation to all paragraphs, h1 and h2 except for those with id='last'

    $('p, h1, h2').not('#last').css({
      'transform': 'translateY(-' + offset * 0.4 +'px)',
      'opacity' : fade
    });

  }
  });
p, h1 {
  font-family: Baskerville;
  margin: auto;
  max-width: 650px;
  color: #333;
}

p {
  font-size: 21px;
  line-height: 33px;
  max-width: 650px;
  margin-top: 30px;
}

p:nth-child(2):first-letter {
  font-family: Arial;
  font-weight: 700;
  float: left;
  font-size: 72px;
  line-height: 63px;
  padding-right: 12px;
}

h1 {
  font-size: 47px;
  margin-top: 30px;
}

h1:last-child {
  margin-bottom: 0px;
}

.container {
  margin-top: 5%;
  margin-bottom: 50vh;
}
   <div class="container">
    <h1>Hello!</h1>

    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam ornare dictum ligula. Maecenas elementum suscipit nisl. Cras imperdiet leo ac felis dictum luctus. Pellentesque odio nisi, accumsan nec, scelerisque sed, consectetuer nec, justo. Sed tortor sapien, suscipit id, pulvinar vel, elementum id, lorem. Nullam consectetuer risus sit amet nibh. Vestibulum consectetuer, quam vitae eu...
    
    <h1 id="last">See ya!</h1>
    </div>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

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

Tips for correctly positioning CSS elements:

I am currently working on a slider using noUi Slider and aiming for an elegant solution. To accommodate the large size of the handle, I expanded the base UI with extra values which are not allowed, causing the handle to jump back to the permitted values. T ...

Layering numerous backgrounds (Regular, Expanded, Regular) atop one another

After experiencing an issue with the background image not fitting the content properly at different resolutions, I attempted to divide the background into three parts and automatically stretch the middle section to fill the space between the top and bottom ...

Customize the background color of Material UI input components on standard labels

Currently using react material ui and interested in changing the background color of a standard input. The issue arises when the label is overridden by the background color when the input is not selected. Input selected Input not selected This is my att ...

When a parent element uses the flex property and its child elements have no content, the flex child will expand

I am experiencing a peculiar issue that has left me puzzled. p { padding: 0; margin: 0; } .fc { display: flex; flex-direction: column; } .fc > article { flex: 1 1 auto; display: flex; flex-direction: column; border: 1px solid #000; ...

The type 'ReadableStream<any>' cannot be assigned to the parameter type 'ReadableStream'

Is there a way to convert a Blob into a Readable format? import {Readable} from 'stream'; const data: Blob = new Blob( ); const myReadable: Readable = (new Readable()).wrap(data.stream()); myReadable.pipe(ext); Encountering an error: ERROR in s ...

Introduce new router events, routeChangeStart and routeChangeComplete, within the client-side components of next js 14

I am currently working on a Next.js v14.0.4 project and I am facing an issue with implementing a top loader progress bar using the NProgress package for route changes triggered by Link or router.push(). The handleRouteChangeStart and handleRouteChangeCom ...

Passing dynamic scope from Angular to a directive is a seamless process

I am working with a directive that retrieves an attribute value from an http call in the following manner: Controller app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); ...

Creating atomic controller actions in Sails.js: A guide to optimizing your controller functions

If I am looking to perform multiple operations within a Sails.js controller, how can I ensure that these actions are atomic to maintain the correctness of the results? This includes not only database operations but also various Javascript processing tasks. ...

When using jQuery each method, it may return an [object Object]

Having an issue with the html variable displaying [object Object] instead of actual elements. Any suggestions on what I should change? var html = ''; $.each(data.response, function(index, value) { var tr = $('<tr>'); var ...

Utilize $.Ajax() to send JSON data using a POST request

I am experiencing an issue while trying to send a JSON object using $.ajax() in jQuery with a POST method from my pure HTML page to a datapower endpoint. The response header in Firebug displays "internal server error." Can anyone help me identify the mis ...

A simple way to initiate an AJAX call once the page has completed loading is by using the `window.location.href` as the

I encountered an issue with my event listener setup function navBtn() { $('#navBtn').on('click', (event) => { window.location.href = 'someotherfile.html'; myAJAXrequest(); }) } The problem I'm facing is that ...

What is preventing my cookie from being saved?

Whenever a user clicks "sign in", I trigger a POST ajax request. Here is the function handling that request: app.post('/auth', function(req,res,next){ var token = req.body.token ...

I am trying to move to a different page, but for some reason the router.navigate function is not functioning within the subscribe

//I am attempting to redirect to another page once the subscribe method is executed, however I am encountering issues with the router.navigate function within the subscribe method. //In an effort to address this issue, I have attempted to store the data r ...

Incorporate the AngularJS controller into your JavaScript code

I am facing an issue with my jQuery UI dialog that contains a dynamic <select> populated with Angular and AJAX. The problem is that the AngularJS script still runs even when the dialog is not visible. To solve this, I added a condition to stop the s ...

Display JSON information in a table using AngularJS

As I delve back into an old project, I've encountered a hurdle. My goal is to display some data in a table, but I seem to have forgotten the intricacies of working with JSON objects and Angular. The API response I'm receiving looks something lik ...

"Troubleshooting the lack of functionality in nested ajax calls, click events, or event

Initially, a navigation click event was created: $('#inner-navigation li a') .on('click', function (e) { e.preventDefault(); AjaxNavUrl.checkURL(this.hash); }); This event triggers an ajax call and respo ...

Receiving a ReferenceError occurs when utilizing JQuery getJSON along with additional JavaScripts

As part of a project, I created a basic HTML page to test JQuery's getJSON method. The code snippet below shows the implementation: <script type="text/javascript"> function test() { $.getJSON("http://api.flickr.com/services/rest/?&metho ...

Challenges with implementing ng2-auto-complete in Angular2

I successfully integrated the Angular 2 ng2-auto-complete component into my project by following this helpful tutorial. The code is also available on GitHub. The current challenge I am encountering involves the formatting of my data source. It is structur ...

Using JavaScript to enhance and highlight specific items in a dropdown menu

I am looking for a solution to prevent duplicate selections in multiple select dropdowns. I want to alert the user if they have chosen the same value in more than one dropdown. Should I assign different IDs to each dropdown or is it possible to use just on ...

Why won't my controller function fire with ng-click in AngularJS?

I'm having trouble getting a function to execute when my button is clicked. Despite the fact that this code appears correct, the function defined in my controller isn't being triggered. The code compiles without errors as shown in the console. A ...