Modifying Background Images Dynamically with jQuery as You Scroll

Struggling to make my background image change while scrolling has been a challenge for me. I've tried different solutions suggested for similar questions, but so far no success - it only displays the initial background image.

The setup involves having the background positioned as fixed and multiple divs, each with the same size as the viewport and a top margin equal to the height of the viewport. This means that the user will see the background image only after scrolling past each div. What I want is for the background image to switch after passing each div.

Below is the code snippet:

$(window).scroll(function() {
    var windowY = $(window).height();
    var scrolledY = $(window).scrollTop();
    var image_url = '/images/image1.jpg';

    if (scrolledY > windowY) {
        image_url = '/images/image2.jpg';
    }

    $('body').css('background', "url(" + img_url + ")");
});

Any help or suggestions would be greatly appreciated!

Answer №1

You made a couple of typos in your code, specifically with the parentheses and the variable name image_url. Originally, you wrote:

$(body).css('background', "url(" + img_url) + "'";

Corrected version:

$(body).css('background', "url(" + image_url + ")");

The issue was with the incorrect placement of parentheses and the improper concatenation of strings. Additionally, you declared the variable as image_url, but used img_url in the css function.

Answer №2

Update the reference to your background image

$(window).scroll(function() {
    var windowHeight = $(window).height();
    var scrolledHeight = $(window).scrollTop();
    var imageURL = '/images/old-image.jpg';

    if (scrolledHeight > windowHeight) {
    imageURL = '/images/new-image.jpg';
    modifyBackground(imageURL);
    }
});


function modifyBackground(imgURL){
  $("body").css("background-image", "url(" + imgURL + ")");
}

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

jQuery fadeIn effect happening at rapid speed

I am currently working on integrating ajax with WordPress. After the ajax call is completed, I am successfully fading out a specific div slowly. However, when trying to fade in the new data using jQuery's fadeIn() method, I noticed that regardless of ...

Creating dynamic HTML table rows with data from a JSON object

Query: In search of a Jquery or JavaScript solution for generating dynamic table rows with colspan using the JSON structure provided below. I am encountering difficulties in creating the necessary rows and have attempted several approaches without success ...

Issue with alignment of divs causing them to stack in a strange manner instead of floating left and

Check it out in action right here: All I want is for the .news div boxes to gracefully float left and right using the handy cycle helper in Rails. However, the current output isn't quite what I had in mind: This is how I envision the layout should l ...

PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements. <script src="h ...

What is the best way to ensure an image is responsive in CSS and aligns perfectly in height with its neighboring text?

There is an image within the <img> tag and some text inside the <p> tag, both enclosed in a <div>. Although the image is responsive and resizes proportionally when the browser window changes size, there is an issue where as the text wrap ...

The JavaScript jump function quickly moves back to the top of the webpage

Issue Resolved To prevent the view from jumping to the top of the page, I have implemented three options: Set the href attribute to href="#!" Set the href attribute to href="javascript:;" Pass the object to the event-handler and preve ...

Retrieve the value of a dynamically added or removed input field in JQuery using Javascript

Check out this informative article here I'm looking for a way to gather the values from all the text boxes and store them in an array within my JavaScript form. I attempted to enclose it in a form, but I'm struggling to retrieve the HTML ID beca ...

Is it possible to modify the CSS of a parent element in vue.js only for the current router route?

I am trying to modify the parent component's style without affecting the CSS of other components. Here is an example from my code: App.vue <div class="page-content"> <router-view ref="routeview"></router-view> </div> rou ...

Revamp the design of the Google image layout

I am trying to replicate the layout of a Google search results page. My goal is to have a full-width div appear on screen when an image is clicked, with a small triangle at the bottom of the clicked image. I attempted to place the img inside another div, ...

ways to run php script based on screen resolution or size

I have 2 php files that I need to execute based on screen size. include_once('large.php'); include_once('small.php'); The condition is to run large.php when the screen size is greater than 992px, and small.php when the screen size is ...

What could be causing the delay in populating 10,000 records in the jquery DataTable()?

I've been working with the Jquery DataTable() library and have noticed that it takes a long time to populate if the data array exceeds 10,000 entries. var newTable = ''; var ref = firebase.database().ref("Students/"); ref.on('child ...

Having trouble parsing PHP JSON encoded data in JavaScript

When I make an AJAX call to a PHP script that returns a JSON encoded object, I encounter some issues. $.post("php/getCamera.php", { cam_id: identifier }, function(data){ console.log(data); //var camera = JSON.parse( ...

jQuery Waypoints - multiple functions appear to be conflicting with one another

Greetings everyone on StackOverflow! I am facing an issue with jQuery Waypoints and couldn't find a solution for it. As a beginner in coding, please bear with me if the solution is simple. My website consists of five sections that appear like individ ...

Troubleshooting height adjustment for header and footer in CSS with dynamic content not functioning properly on Safari for macOS and Safari for iOS (jsBin)

I recently came across a solution by @RokoC.Buljan, which works perfectly on Chrome and Firefox. However, I encountered an issue with Safari where the content section does not scroll properly and the footer sticks to the bottom of the content, making it di ...

Curious as to why body.scrollTop functions differently in Google Chrome and Firefox compared to Microsoft Edge

Up until recently, the code body.scrollTop was functioning correctly in my Chrome browser. However, I've noticed that now it is returning 0 in both Firefox and Chrome, but still giving the proper value in Microsoft Edge. Is there anyone who can assis ...

Creating a jQuery plugin with configurable options but without attaching it to any specific HTML element can be

I am currently working on developing a unique plugin that does not require a DOM element but comes with default options pre-set. However, upon executing the code snippet below, I encounter the error message TypeError: $.myApp is not a function. What modi ...

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

Is there a sophisticated CSS compressor that can eliminate unnecessary code and separate identical rules with commas?

Consider this input{margin:0}body{margin:0;background:white} can also be written as input,body{margin:0}body{background:white} or like this input,body{margin:0}body{margin:0;padding:0} and simplified to input,body{margin:0}body{padding:0} Bottom Li ...

Refresh a function following modifications to an array (such as exchanging values)

Looking to re-render a function after swapping array values, but the useEffect hook is not triggering it. I need assistance with this as I plan to integrate this code into my main project. Below are the JSX and CSS files attached. In App.js, I am creating ...

Trouble with AJAX not properly fetching PHP JSON response

I recently encountered an issue with my jQuery AJAX request that sends user input to a PHP file. Initially, the code worked perfectly fine but adding "dataType: 'json'" caused it to malfunction. Here's how I set it up: $.ajax({ url: url ...