Function that is triggered by scrollbar height indicator

I'm currently utilizing jQuery to retrieve the user's current height and triggering an animation function once they reach that height (similar to reactive websites where animations occur as the user scrolls down the page).

However, I am struggling to understand why the code below is not functioning properly.

$(window).scroll(function() {
    var height = $(window).scrollTop();

    if(height  > 200) {
      $("#project").animate({
        bottom: '250px',
        opacity: '0.5',
        height: '1000px',
        width: '100%'
      });
    }
});

CSS:

/*       About Page        */
.about{
  width: 100%;
  height: 1000px;
  background-color: blue;
}
/*       Projects Page        */
.project{
  background-color: red;
}

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="css/style.css" />
    <script src="jquery-3.4.1.min.js"></script>
    <script src="myscripts.js"></script>
    <title>My Portfolio</title>
  </head>
  <body>
    <div id="about" class="about">

    </div>
    <div id="project" class="project">

    </div>
  </body>
</html>

How can I utilize a scrolling height indicator to trigger functions like animations?

Answer №1

To ensure smooth animations when reaching certain elements, consider factoring in the height of each section and determining the scrollBottom position:

const $about = $('#about');
const $projects = $('#projects');
const $services = $('#services');

// Calculate the top offset of each section (number of sections above it * 1000px each).
// To trigger expansion when 50px above the element, subtract that amount.
let projectTop = 1000 - 50;
let servicesTop = 2000 - 50;

$(window).scroll(() => {
  requestAnimationFrame(() => {
    // Determine scrollBottom by adding the viewport's height:
    const scrollBottom = $(window).scrollTop() + $(window).height();

    if (scrollBottom >= projectTop) {
      $projects.animate({ height: '1000px' });
    }
    
    if (scrollBottom >= servicesTop) {
      $services.animate({ height: '1000px' });
    }
  });
});
body {
  margin: 0;
}

.about {
  background: red;
  width: 100%;
  height: 1000px;
}

.projects {
  background: green;
  width: 100%;
}

.services {
  background: blue;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="about" class="about"></div>

<div id="projects" class="projects"></div>

<div id="services" class="services"></div>

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 retrieve an object that needs to be defined within a function?

I am struggling to get my imported obj model to move using three.js. There seems to be a formatting issue where the obj object needs to be declared inside a function, making it inaccessible outside of that function even if I pre-declare a variable to poi ...

how to check if a string has white spaces in a react application

If the input string has white space, the alert will indicate unsuccessful. If the input string does not have any white space, the alert will be successful. import React from "react"; export default function DropDown() { let i = document.getEle ...

Prevent caching of JavaScript variables in EJS mode

Is there a way to turn off ejs cache? I came across a solution: ejs.clearCache() However, this method requires an instance of ejs to work. Currently, I am only using: app.set('view engine', 'ejs'); Therefore, I am unsure how to cle ...

How can I convert Double Quotes from (") to (&quot;) in TinyMce Editor?

While using TinyMce Editor, I have encountered a problem with double quotes breaking my code. In the HTML source of TinyMce, it displays " instead of &quot, causing issues in conversion. It seems that it is not converting " to " as it should, simi ...

What could be causing my insertRow function to inject empty cells into my table?

I am facing an issue with adding the results of a fetch request into a table as a new row. Strangely, when I click the button to trigger this function for the first time, it adds an empty row instead of the desired data. However, on subsequent clicks, the ...

If a table column lacks an unspanned cell, IE will disregard its width

Here is a visual representation of the issue I am facing: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <body> <table border="1"> <colgroup> <col ...

Mastering the art of transforming JSON data for crafting an exquisite D3 area chart

I often find myself struggling with data manipulation before using D3 for existing models. My current challenge is figuring out the most efficient way to manipulate data in order to create a basic D3 area chart with a time-based x-axis. Initially, I have a ...

Access a local website path using JavaScript upon opening the browser

I need a Javascript function that can determine the day of the week when my html file is accessed, allowing me to automatically open a specific sub-page within my project. ...

Output repeated JSON Array in console using Node.js

Looking to identify duplicates within a JSON array based on the URL. var temp = [ { "name":"Allen", "site":"www.google.com/allen" }, { "name":"Chris", "site":&q ...

Storing and securing passwords in Node/Express using hashing and salting techniques

Utilizing the Crypto module within Node's standard library is a necessity. I have established a POST route dedicated to handling a registration form: app.post('/superadmin/add-account', function(req, res) { // Creating shorthand variable ...

jQuery: Remember to re-bind the form when it is returned successfully

Just a quick question: I'm currently using the jQuery.forms.js plugin. My situation involves a form that posts to a PHP page and receives data in JSON format. The returned data contains code for a new form, which replaces the original form used to s ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...

Is it possible to use both "npm install --global" and "--save" simultaneously?

I'm curious if it is practical to use both the --global and --save parameters in the npm install command simultaneously. For instance: npm install gulp -g -s From my understanding, since there is no package.json in the npm system folder, I assume th ...

Jquery Enhancement for Navigation

Recently, I have implemented a header and footer navigation on my website. The header navigation consists of 1 UL (unordered list), while the footer navigation comprises 5 ULs. My goal is to align the first child of each UL in the footer navigation with th ...

angular-recaptcha: Adjusting language based on the website's language update

My website offers three different languages that users can switch between. The language switch functionality is implemented on the client side using JavaScript (AngularJS). I have integrated reCAPTCHA 2 into my website and now I need to update the languag ...

The issue of jumpy CSS background on full screen mode for mobile devices is causing

While developing a web app, I encountered an issue with the responsive (parallax) full screen background. On mobile devices, the background does not extend below the toolbar, causing a jumpy effect when scrolling up and down in Firefox. I have tried differ ...

JavaScript and jQuery: The Power of Dynamic Arrays

Even though my var email contains a string data, why does my array length always turn out to be 0? (I've confirmed that the data is there by using alert on var email). var emails = new Array(); //retrieve all the emails $('.emailBox ...

Do server-side or client-side rendering render dynamic routes in Next.js?

I'm currently working on a project that necessitates server-side rendering for SEO benefits. I am utilizing Next.js and React, implementing Next.js dynamic routing for this purpose. To test if the setup is functioning correctly, I developed a basic p ...

Working with Python and BeautifulSoup to retrieve <td> elements in a table without specified IDs or classes on HTML/CSS documents

While utilizing Selenium, Python, and Beautiful Soup to scrape a web page, I encountered the challenge of outputting table rows as comma-separated values due to the messy structure of the HTML. Despite successfully extracting two columns using their elemen ...

Retrieve the properties from within a closure function in a functional component

I have developed a simple React application using create-react-app. The app consists of a single component that takes in a value and an onClick callback. When the callback is triggered, the value increments. import React, { useState } from 'react&apos ...