Effortless jQuery Parallax

Seeking assistance with debugging this jQuery code that manipulates the top margin of an element within a container. The container has a fixed size and overflow set to hidden to create a parallax effect. The parallax effect is functioning properly, but it breaks if the page is reloaded after scrolling even a single pixel. Any suggestions on how to resolve this issue? Below is the code snippet.

// Parallax for Header
$(window).on("load", function() {
    var startingScrollTop = parseInt($(window).scrollTop());
    console.log(startingScrollTop);
    var startingElementTop = parseInt($headerText.css("margin-top"));
    console.log(startingElementTop);
    $(window).on("scroll", function() {
        var currentScrollTop = parseInt($(window).scrollTop());
        console.log(currentScrollTop);
        if (currentScrollTop > startingScrollTop) {
            var scrollDistance = currentScrollTop - startingScrollTop;
            console.log(scrollDistance);
            var parallaxDistance = scrollDistance / 2;
            console.log(parallaxDistance);
            var newElementMarginTop = startingElementTop + parallaxDistance;
            console.log(newElementMarginTop);
            $headerText.css("margin-top", newElementMarginTop + "px");
        } else if (currentScrollTop <= "0") {
            $headerText.css("margin-top", "0px");
        }
    });
});

Your help is greatly appreciated.

Answer №1

I've managed to solve it, but is there a way I can simplify this further?

//Parallax for Header
$(window).on("load", function() {
  var startingScrollTop = 0;
  console.log(startingScrollTop);
  var startingElementTop = parseInt($headerText.css("margin-top"));
  console.log(startingElementTop);
  
  function runParallax() {
    var currentScrollTop = parseInt($(window).scrollTop());
    console.log(currentScrollTop);
    
    if (currentScrollTop > startingScrollTop) {
      handleParallaxEffect(currentScrollTop);
    } else if (currentScrollTop <= 0) {
      $headerText.css("margin-top", "0px");
    }
  }
  
  function handleParallaxEffect(scrollTop) {
    var scrollDistance = scrollTop - startingScrollTop;
    console.log(scrollDistance);
    var parallaxDistance = scrollDistance / 2;
    console.log(parallaxDistance);
    var newElementMarginTop = startingElementTop + parallaxDistance;
    console.log(newElementMarginTop);
    $headerText.css("margin-top", newElementMarginTop + "px");
  }
  
  //Run on load
  runParallax();
  
  $(window).on("scroll", function() {
    runParallax();
  });
});

Is it possible to encapsulate the re-used code into a function that can be executed on load, scroll, or any other event handler?

Answer №2

Once again, disregard my previous statement, I have successfully completed it:

for those who are interested:

//Implementing Parallax Effect for Header
$(window).on("load", function() {
  var startingScrollTop = 0;
  console.log(startingScrollTop);
  var startingElementTop = parseInt($headerText.css("margin-top"));
  console.log(startingElementTop);
  
  //Function to create parallax effect on scroll
  function parallaxify() {
    var currentScrollTop = parseInt($(window).scrollTop());
    console.log(currentScrollTop);
    
    if(currentScrollTop > startingScrollTop) {
      var scrollDistance = currentScrollTop - startingScrollTop;
      console.log(scrollDistance);
      var parallaxDistance = scrollDistance / 2;
      console.log(parallaxDistance);
      var newElementMarginTop = startingElementTop + parallaxDistance;
      console.log(newElementMarginTop);
      
      $headerText.css("margin-top", newElementMarginTop + "px");
    } else if(currentScrollTop <= "0") {
      $headerText.css("margin-top", "0px");
    }
  }
  
  parallaxify(); //Initial execution
  
  $(window).on("scroll", function() {
    //Execute the same code on scroll event
    parallaxify();
  });
});

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

Leveraging kubectl.exe in conjunction with Docker and Node.js

I am currently attempting to execute my kubectl.exe file within a Docker environment. The version of kubectl is 1.26.2 and the Kustomize version is v4.5.7. Running everything successfully locally with npm start, however when trying in a docker container, ...

Centralized navigation bar

I am currently facing a challenge with centering my nav bar and I'm not sure how to proceed. The nav bar is placed within a class and a div, which is causing confusion for me. I have attempted to align it to the center and also tried using float:cente ...

A peculiar issue is occurring in Vue.js where a value within a v-for loop seems to be losing association with the intended array

During my third day of working with Vue.js, I decided to create a basic application for requesting car keys in a service department. Although I am aware that there are areas in the code that could be improved, I encountered a specific issue that I need ass ...

what is the significance of the number THREE in the context of Three.js?

Can you explain the significance of "THREE" in three.js? When we are creating a scene or any object, we typically use names like new THREE.Scene() or new THREE.WebGLRenderer(). What is the meaning behind the term "THREE" in this context? ...

Creating dynamic HTML and CSS in ASP.NET: A step-by-step guide

I am currently working on integrating a photo album in my asp.net website. I have been able to successfully display 3 images from a specific album by selecting their URLs from the database. However, I am facing an issue when a user has multiple albums. I n ...

Having difficulty invoking a JavaScript function through PHP

My goal is to achieve the following: <html> <script type="text/javascript" src="jquery.js"></script> <a id="random">before</a> <script> function test(a) { document.getElementById('random').innerHTM ...

Create a box with borders and divisions using HTML

Hello, I am trying to create a box in HTML with a slanted divider line inside. How can I achieve this design? I am aiming to replicate the layout shown in this image: Link to Image I have tried implementing the code below, but the alignment is not matchi ...

Issue: The hook call is invalid. In React Native, hooks can only be called within the body of a function component

While attempting to utilize useSelector within the component, I encountered an error message stating: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. backgroundTasks.js: import axios from "axios"; i ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

the content outside of the division is incorrectly formatted

Here is the code snippet that I am working with: <html lang='es'> <head> <link rel="stylesheet" type="text/css" href="theme.css"> <link rel="stylesheet" type="text/css" href="bootstrap337/css/bootstrap.mi ...

Does CSS positioning change depending on the screen size?

I need help fixing the positioning of my logo on the screen. I want it to be 40px from the top and centered horizontally regardless of the screen size. Here is the code that I have: <html> <head> <style type="text/css> body{ back ...

What is the best practice for handling AJAX and API calls within React.js function components?

Recently, I've been delving deeper into React.js function components and am in the process of transitioning one of my React.js applications to utilize them instead of the traditional react components. In my previous react components, I used to make AJ ...

I am looking to insert the indexes of an array into a table data cell (<td>), with the select options being the array's indexes

I'm looking for a way to add the indexes of an array as options in a select field. However, the code provided below is not working as expected. <?php $str4 = "select * from fee_names where status = '1' "; $res4 = mysql_quer ...

What is the best way to toggle between display:none and display:block?

How can I delay the appearance of mobile nav items without using JS until the nav overlay fully expands for 0.4s? In the non-overlay state, the top nav has a hamburger menu on the left and my name on the right with hidden nav links. When in the overlay s ...

JavaScript anchor scrolling

I am currently working on building a website with anchor navigation similar to what is used on platforms like Facebook and Google Mail. I have managed to get it partially working, but there are still some issues. For example, when I load the page with some ...

Programmatically remove a component from the DOM in Vue 3

I am working on a project similar to a spreadsheet with draggable cells, where I can move events, which are components, around. One of the challenges I'm facing is removing a component after adding it dynamically. I have tried using this code snippet ...

Issue where the background color remains the same and does not change

I'm having trouble identifying the issue in this code. I am attempting to change the background color using the following CSS: body { background-color: black; padding: 0px; margin:0px; height: 1500px; } However, it doesn't seem to ...

Implementing ID-based filtering for an array of objects with React

Struggling with filtering an object in an array of objects by its ID using React. Here's the scenario: The app is a Notes app that stores each note with its Title, Text, and created date, utilizing the ID as the key. Currently, I'm working on c ...

When sending a POST request, the req.body.someElement parameter is not defined

Encountering an issue with a post request, as req.body is returning undefined values. Despite researching on Google and Stack Overflow, the provided solutions have not resolved the problem. Although logging the name shows a value, trying to access req.body ...

Is there a way for me to pinpoint the location of an error in React?

Currently, I am operating a basic React application with webpack in development mode by using the following command: webpack -w --mode development --config ./webpack.config.js This setup ensures that my code remains unminified. However, I am encounterin ...