Changing the background on scroll using JavaScript and JQuery

Seeking a method to create a dynamic background image for different sections on a one-page website, I encountered difficulty in finding suitable examples online. After browsing through various questions on Stack Overflow, I attempted to implement the following code:

<style>
    body {
        background-image:url('http://7-themes.com/data_images/out/39/6901356-free-background-images.jpg');
    }
</style>
<script type="text/javascript">
    $(window).scroll(function() {
        var image_url = 'http://7-themes.com/data_images/out/39/6901356-free-background-images.jpg';
        if ($(window).scrollTop() > 800) {
            image_url = 'http://www.designbolts.com/wp-content/uploads/2014/03/Yellow-blur-background1.jpg';
        }
        $(body).css('background-image', image_url);
    });
</script>

However, this code does not appear to be functioning as expected. I am unsure of what is causing the issue and how it can be resolved, especially considering that the website needs to be responsive across various resolutions.

Answer №1

$(window).scroll(function () {
    var img_url = 'http://7-themes.com/data_images/out/39/6901356-free-background-images.jpg';
    console.log($(window).scrollTop());
    if ($(window).scrollTop() > 800) {
        img_url = 'http://www.designbolts.com/wp-content/uploads/2014/03/Yellow-blur-background1.jpg';
    }
    $('body').css('background-image', 'url(' + img_url + ')');
    //^^^^^^                          ^^^^^^               ^^^   
});
body {
    background-image:url('http://7-themes.com/data_images/out/39/6901356-free-background-images.jpg');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>

Answer №2

The syntax provided is incorrect; it should be corrected to:

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

You can also attempt the following code snippet:

if($(this).scrollTop() > 800)

Answer №3

This particular script can be quite helpful for ensuring that your website background image changes dynamically as you scroll (similar to what was mentioned in other responses):

$(window).scroll(function() {
    var image_url = 'http://7-themes.com/data_images/out/39/6901356-free-background-images.jpg';

    if ($(window).scrollTop() > 800) {
        image_url = 'http://www.designbolts.com/wp-content/uploads/2014/03/Yellow-blur-background1.jpg';
    }

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

However, imagine a scenario where you need the image to change not at 800 pixels but at a different point like 900 pixels. In such cases, rather than hardcoding the value in your code, it's advisable to utilize the

$("#whateverSection").offset().top
variable. For a demonstration, refer to this jsFiddle link.

By adopting this approach, you have the flexibility to determine which image should appear when specific sections of your site are scrolled into view.

$(window).scroll(function() {
    var image_url = 'default.jpg';

    if ($(window).scrollTop() > $("#section1").offset().top) {
        image_url = 'img1.jpg'
    }
    else if ($(window).scrollTop() > $("#section2").offset().top) {
        image_url = 'img2.jpg'
    }
    ...
    else if ($(window).scrollTop() > $("#sectionX").offset().top) {
        image_url = 'imgX.jpg'
    }

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

Answer №4

Ensuring compatibility

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

Double check your selector for accuracy

https://jsfiddle.net/js7tadve/

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

I am experiencing challenges with utilizing the fetch() function and am unable to retrieve the data

I'm currently struggling with integrating Google's reCaptchaV3 into my website, particularly when using the fetch() function. Here is the code snippet I have developed so far: function sendData(name, email, captcha) { const info = JSON.stri ...

Concurrent Openlayers maps in Rails - A Viable Option

I've been playing around with Openlayers maps on my website. The map functionality is working perfectly, but I'm having trouble getting the maps to display correctly on my page. My goal is to show a map in each search result on my screen - one m ...

Guide to implementing Vuetify tabs alongside Vue Router

I have a scenario with two Vuetify tabs in this jsfiddle, but the documentation lacks examples of using vue-router with them. After stumbling upon a helpful Medium.com post about integrating Vuetify with vue-router, I came across the following code: <d ...

"Utilizing a media query to display an anchor link at the top based

How can I create a "Back to Top" link that automatically scrolls mobile and tablets to the top of the page? Usually, I would achieve this using JavaScript by detecting the window and body height. Is it possible to accomplish this using a media query? @me ...

Generating dynamic colors from a map in SASS within a media query function

Utilizing @include-media for SASS breakpoints (). Seeking to create a dynamic breakpoint helper text that changes background color on various media sizes. Important Breakpoint mixin - https://raw.githubusercontent.com/eduardoboucas/include-media/master/d ...

Exploring the World of MVC 4: Delving into Modal Windows, Partial Views,

I am currently utilizing MVC4 along with Entity Framework to build a web application. Within my database, I have a table listing all the individuals. Each person can have their information edited through a modal window that is implemented as a Partial View ...

Loading FBX files with Textures in Three.js

After obtaining a fbx file with textures from this link, I attempted to open it using three.js: var loader = new THREE.FBXLoader(); loader.load('models/fbx/myfile.fbx', function(object) { scene.add(object); }, (ev) => { console.log(e ...

rescaling and replicating a pattern in three.js

I have a large plane with a set displacement map and scale that I want to remain unchanged. I just need the loaded texture to be applied to the mesh without scaling up too much. Right now, a floor texture doesn't look natural because it has been enla ...

Guide on integrating a HemisphereLight into a basic Three.js environment

I've been experimenting with adding light to a simple scene in threejs, but no matter what intensity or color I set for the light, there is no visible change. Strangely, even when I exclude the light code altogether, nothing happens either. Why is Hem ...

Issue with Django where only one out of six buttons is assigned the jquery popup window

Currently developing a cookbook website and facing a challenge. Attempting to integrate django pagination with a sleek popup jquery plugin found at this link: Encountering an issue where only the first recipe button activates the popup window, displaying ...

centered table within a container with vertical alignment

I'm having trouble centering a table vertically in a div. I've tried using vertical-align but it's not working for me. Can anyone suggest a solution to place it at the top of the div? <div class="col-12 d-flex"> <div c ...

Streaming large files with Node.js can lead to significant memory consumption and potential memory errors like OOM

My current project involves using node.js to download large files (300MB) from a server and then piping the response to a file write stream. While I have a good understanding of how pipes work in Node.js, I am encountering an issue where the memory usage o ...

Transferring data from AJAX form in JavaScript to PHP function

My website features a login form that sends data, such as email address, to a PHP function and initiates the creation of a user. I am looking to include additional information on the page where the form is located. Here is the data I want to include in t ...

Set a predefined height for an element, yet ensure it adjusts to fit within its container (with the option to overflow only if it reaches a minimum specified height)

Consider this setup: A heading text a main content block All inside a single parent container. .outer { max-height: 200px; background-color: green; } .inner { min-height: 50px; /*for illustration, default height is set higher than ou ...

Issue with RestAngular: The put and customPUT methods are sending the outdated object instead of the updated one

Every time I use the put or customPUT method and inspect the request body in the browser, it always sends the original object instead of the updated one. Interestingly, when I check the RestAngular object with a {{ object }}, it clearly shows that it is be ...

Executing a dropdown menu click event using PHP and AJAX

I need to display associated data when a user selects an option from a dropdown list. Below is the code for the dropdown list: <select class="op" name="emp" id ="tab4"> <option value="">--Select--</option> <?php foreach ...

Vue-router with a Google Inbox-inspired navigation interface

I am currently in the process of developing an app using vue-router with the goal of achieving a user interface similar to that of Google Inbox or possibly the Techcrunch homepage. Specifically, I want to have a list of items where clicking on one item exp ...

Troubleshooting Challenges in JavaScript/jQuery Hangman Game

Having trouble with my hangman game's game loop. Attempting to replace correct letters as the game runs through the word, but it's currently: looping through the word checking if the guessed letter is in the word returns index[0] Tried splitti ...

Cross-Domain Communication with XMLHttpRequest

I am facing an issue with the code snippet below: console.log(1); var xhr = new XMLHttpRequest(); xhr.open('POST', 'http://anothersite.com/deal-with-data.php'); xhr.setRequestHeader('Content-typ ...

Troubles arise when trying to convert a schema using Normalizr

Is there a way to efficiently convert a JSON array containing travel expenses into a format that allows for easy retrieval of expenses by travelExpenseId and tripId? [ { "travelExpenseId":11, "tripId":2, "paymentPurpose":"some payment ...