Adjusting background-position-x while scrolling

I came across Ian Lunn's Parallax tutorial and found it really interesting. The tutorial can be accessed at . My goal is to enhance the effect by not only changing the y-position of the background but also adding horizontal movement based on scroll input. This would make certain objects move in both vertical and horizontal directions simultaneously.

To better explain what I have in mind, check out the example at . Specifically, look at the 3rd scene where the car enters - that's the kind of movement I aim to achieve.

Below is the original code snippet from Ian Lunn:

//function that is called for every pixel the user scrolls. Determines the position of the background
/*arguments: 
    x = horizontal position of background
    y = vertical position of the background
    windowHeight = height of the viewport
    pos = position of the scrollbar
    adjuster = adjust the position of the background
    inertia = how fast the background moves in relation to scrolling
    backgroundPosition-y = original background position vertical
*/
function newPos(x, windowHeight, pos, adjuster, inertia){
    return x + "% " + (-((windowHeight + pos) - adjuster) * inertia)  + "px";
}

//function to be called whenever the window is scrolled or resized
function Move(){ 
    var pos = $window.scrollTop(); //position of the scrollbar

    //if the first section is in view...
    if($firstBG.hasClass("inview")){
        //call the newPos function and change the background position
        $firstBG.css({'backgroundPosition': newPos(20, windowHeight, pos, 300, 0.1)}); 
        sun_1.css({'backgroundPosition': newPos(10, windowHeight, pos, 4000, .1)});
        deer.css({'backgroundPosition': newPos(40, windowHeight, pos, 500, .1)});
    }

Although I'm aware this may not be the best approach, here's what I've attempted:

sun_1.css({'backgroundPosition': newPos(10, windowHeight, pos, 4000, .1)}, {'background-position-x': '0% ' + parseInt(-xx/ 10) + 'px'});

I'm wondering if there's a way to integrate this into the existing "newPos" function?

Answer №1

After some trial and error, I cracked the code on a solution that seems to do the trick.

sun_1.css({'backgroundPosition': newPos((3+pos/50), windowHeight, pos, 4000, .2)});

It might not be perfect, but it gets the job done. The first number sets the initial position (in this case, 3%), the second number tracks the window's scroll position, and the third number determines how fast the movement occurs.

If you want to change the movement direction along the x-axis, just swap out "50" with a negative number.

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

Enhance your CouchDB experience by customizing templates to include unique headers and footers

I am currently using CouchDB and CouchApp to host a web application. I have experience with Django and Jinja2, where I can extend templates in two different ways: {% include "header.html" %} or {% extends "base.html" %} <<<---- my preferred me ...

When a custom header is added, cookies are not included in cross-origin jQuery AJAX requests

An issue arises when sending an ajax request from our main domain to a subdomain (cross-origin) through jQuery. Despite having CORS implemented and functional, we encounter a problem when attempting to include a custom header in the request. The presence o ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

HTTP 400 Error: Bad Request Callback

I'm attempting to send data using REST API through jQuery AJAX. Here's the code I am using: $.ajax({ url: 'myurl', type: 'POST', contentType: 'application/json; charset=utf-8', data: JSON.stringify(j ...

Steps to turn off a Material UI CSS class for an element universally

Utilizing the Material UI Typography element with the css class MuiTypography-h1, I am seeking to globally disable its usage throughout the entire codebase. <Typography variant="h1" sx={{ width: '100px', height: '55px ...

Error 500: Internal Server Issue Detected during AJAX Request in Laravel

I am having issues with fetching dependent select items using an ajax call. I want to display related 'groups' after selecting a 'class', but I keep getting a 500 internal server error in my console. Can someone please assist me in achi ...

Utilize jQuery to apply inline styles to dynamically created div elements

I am attempting to apply inline styles to a div using jQuery. The current state of the div, as seen in Firebug, is shown below: https://i.sstatic.net/rqhIc.jpg My goal is to retain the existing CSS while adding margin-left:0 and margin-right:0 to the cur ...

Displaying Text and Images on a Sliding Carousel with a Static Background Image

I am currently experimenting with the Materializecss Image Slider. My goal is to have a fixed full-screen background image while the texts and images slide over it. Initially, I tried setting the background-color of the slider class as transparent, but un ...

Z-index creates an obstacle that prevents items from being clicked on

I am facing an issue with my container div that has an inset drop shadow applied to it. Inside this container, I have child elements and I want these children to be clickable. For the drop shadow to show, it is necessary to set the z-index of the child el ...

Invoking an ajax request from the success callback of another ajax request

When you click on a singer class button, the name of the singer along with buttons that have the music class and their respective songs (data) are displayed. Clicking on a music class button will show the song lyrics (data2). At this point, I would like ...

Dynamic Retrieval of Data into Textbox by Selecting Dropdown List Option in MVC4

Utilizing Json to populate textbox values from a database based on a selected email address from a dropdown. However, the code is not functioning as expected. Here is the snippet: JQUERY $(function () { GetUserInfo($("#EmailAddress")); }); ...

Unleashing the Power of Wildcards in HTML with XPath

When using XPath to extract values from DOM elements, I've encountered inconsistent XPaths. To select all DOM elements on the same level, I've resorted to some wildcard magic. For instance, in an HTML document, my XPaths may look like: //div[@i ...

How to convert jQuery data into JSON format

I am dealing with data in the following format: ID=300573&CarNo=1&Account=AAAA&AccountingDate=3%2F21%2F2013&Description=NewCar&CheckAmount=666666&ClearedAmount=-3446.5&ClearedDate=4%2F9%2F2013&Sent=S&SentDate=4%2F4%2F20 ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

"Enhance the user experience by enabling clickable preview files in dropzone

After working on my Django project, I have implemented the following: <link href="{% static 'media/dropzone/dist/min/dropzone.min.css' %}" type="text/css" rel="stylesheet" /> <form class="dropzone" id="my-media-dropzone" action="/some/u ...

Jssor Slider: Captions briefly overlap just as the slideshow begins to play

I am currently working on a slideshow with 3 caption-only slides. Here is the code snippet: <div id="sliderHeader_container" style="position: relative; width: 965px; height: 85px;"> <!-- Slides Container --> <div u="slides" style=" ...

Make window.print() trigger the download of a PDF file

Recently, I added a new feature to my website allowing users to download the site's content by following these instructions: Printing with Javascript || Mozilla Dev. Essentially, the user can print a newly formatted site stored in a hidden iframe. Now ...

The collapsible menu located beneath my navigation bar is unable to reach the correct position on the right side

I'm attempting to create a collapsible navigation bar with its contents shifting to the right side when resized to medium size, but I'm having trouble. Can someone please assist me with this? I have also included the code below. <nav class=&qu ...

Stop unwanted scrolling upwards by using jQuery ajax function $.load

I'm currently in the process of creating an ajax chat using jquery and php. Everything seems to be running smoothly except for one issue related to scrolling. Essentially, I've implemented a time-out function that automatically reloads the inner ...

Placing elements in an exact position within a parent container is causing an overlap with the

I am struggling to grasp why a div set as absolute inside a relative div is overlapping with other elements. From what I understand, it should remain fixed within its parent relative div, right? This is my solution: #container { position: relative; ...