Adjust the background of a CSS element using jQuery as the y-axis scroll crosses a specific threshold

Once the user has scrolled 600px down the page, I want a CSS background image to transition from no image to a specific background image (image 1). However, if they scroll above 600px, I want it to switch to another image (image 2). It should be able to continuously repeat this without requiring a page refresh as well.

Below is the code I am using:

jQuery:

$(window).scroll(function() {
    var y_scroll_pos = window.pageYOffset;
    var scroll_pos_test = 800;             
    // set to whatever you want it to be

    if(y_scroll_pos > scroll_pos_test) {
       $("square").css("background-image", "url(images/comp_rel/square.png)");
    }
    else
    {
        $("square").css("background-image","url(images/comp_rel/Box.gif)");
    }
});

I feel like I might be overlooking something simple here, but I just can't seem to pinpoint it. Any suggestions or thoughts would be greatly appreciated. Thank you!

Answer №1

Here is a solution that has been effective for me:

$( window ).scroll(function() {

    var y_scroll_pos = document.documentElement.scrollTop;
    var scroll_pos_test = 800;             
    // adjust this value as needed

   if(y_scroll_pos > scroll_pos_test) {
       $("#square").css("background-image", "url('image.jpg')");
    }
    else
    {
        $("#square").css("background-color", "#0000ff");
   }
})

Simply change the css property from background-color to background-image.

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

An image is downloaded with each AJAX request

Currently I am dynamically updating a table using intervals and AJAX calls. The AJAX call returns HTML, which represents a row that may contain an image if specific data is still being updated. The issue I am facing is that every time the AJAX call is mad ...

onsubmit function was never triggered

Seems like a silly mistake, but I'm encountering an issue with my HTML form. Here's a snippet of the code: <form onsubmit="updateProfile();"> <input type="submit" value="Update Account"> .. ... </form> However, w ...

Utilizing Liferay 6.0.6's JSON API to Enhance JavaScript Functionality

I am seeking a way to access data from the Liferay portal using its JSON API through JavaScript client by making AJAX calls. After some research, I was able to find the address for the API : http://127.0.0.1:8080/tunnel-web/secure/json There is also a S ...

PHP and JQuery not working together to update database

Essentially, I am trying to update the status based on the unique id. Despite no errors being thrown, the status remains unchanged. index.php $(document).ready(function() { $('.seatCharts-seat').click(function(){ var id = jQuery(th ...

What is the best way to invoke a Service from a Directive in AngularJS?

Every time a user clicks, a directive is triggered to change the icon for adding to their favorite list. View: <div class="col col-33"> <i class="icon ion-ios-heart-outline" favorite="place[0].objectId" on-icon="ion-ios-heart-outline" off-ic ...

Getting 6 shots to load simultaneously on Jribbble - how can I do it?

Hello! I'm still getting the hang of Javascript, but I've made progress in loading elements onto the page. As a beginner, this is a good start for me. Currently, I am working on a script to load 6 "shots" onto a page, but it seems to be loading ...

Error: Data type exception encountered in JSP file

Currently, I am developing a web application that involves generating a table dynamically using Ajax. The data for this table is retrieved from the database. Below, you can find the code snippets related to this functionality. Index.jsp <html> <h ...

Generating a table with two columns utilizing ng-repeat

I am currently dealing with an array of objects that I need to showcase in a two-column layout. The challenge arises because some columns have more data than others, requiring equi-height rows. Despite utilizing Bootstrap and clearfix in my attempts to di ...

How to Integrate AngularJS into an HTML Document?

I have a specific goal in mind: to create a single HTML file without separate JavaScript files. While I know that it's possible to include JavaScript inline within HTML, I'm unsure if the same applies to AngularJS. I've attempted to integrat ...

Is it possible for amCharts to show the data properly?

Starting out with amCharts and javascript can be a bit overwhelming. Here is the structure of my html file: <!DOCTYPE html> <html> <head> <link rel="shortcut icon" href=""> <title>chart created with amCharts | amChar ...

What is the best way to populate a dropdown menu in PHP?

I am trying to populate my combobox with names from an SQL database. I came across some code on W3schools, but I am having trouble integrating it into my own code. Currently, the combobox is filled with select, but that's not the intended functionalit ...

The event handler on line 72 triggered an error that was not handled, resulting in an error message indicating a permission issue on OpenShift: "Error: cannot listen for connections

I have been working on creating a basic chat app. Initially, it was running smoothly on localhost:3000/chat.html. However, upon deployment on OpenShift, I encountered a crash accompanied by the following error message (as seen after running rhc tail): UPD ...

Tips on scrolling the web page until the desired web element is visible and carrying out necessary tasks

When searching for input, multiple table data is retrieved. A "show as text link" is present in different table rows that needs to be clicked. I wrote a code that works fine in IE on one machine but does not work on a different machine due to variations i ...

utilize php mail() function to send emails in html format

In my CodeIgniter project, I have created a function using PHP mail() to send emails. Here is the code snippet: function mailsend() { $to="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd2c6d2ded6d3ffd8d2ded6d391dcd0d2"& ...

Is there a way to transfer the value from dropbox when clicking on a submit button in a Http

I am currently working on passing the value of a droplist to a get action. The submit button redirects to the correct action, but I am unsure of the correct method to include the droplist value with the redirection. This is my view: @model TrackerModel ...

Locate the customers' IP addresses through an application built with ExpressJS

A few days back, I created a nodejs script for capturing user agents. While my script was functional, I faced difficulties in logging the REMOTE_ADDRESS of the client. app.js: var express = require('express'), http = require('http'), a ...

What is the most effective way to use checkboxes to apply multiple filters to an array of objects?

Let me simplify the description. Within the App component, I fetch data from a JSON file and store it in the flightsList array. My goal is to filter this array based on checkboxes selected in the FlightOptions and Airlines components. The issue that I&a ...

How can the object currently being dragged be chosen using JQueryUI Draggable?

Working with JQueryUI draggable, I am interested in applying styling to the draggable element while it is being dragged. Various attempts have been made using code like this: $(".ui-widget-content").draggable({ drag: function(event, ui) { $(this).cs ...

Positioning a flash element in the center

Struggling to find the perfect alignment for a flash widget on this particular page . Experimented with using both the <center> tag and various other methods, but alas, it remains stubbornly off-center. If anyone has any suggestions or solutions, p ...

Position the text to line up perfectly alongside the floating image

How can I use the float property to align text and images? The text marked in red should be positioned next to the floating image, but for some reason I am having trouble getting it in the right place. https://i.sstatic.net/gfuu6.png This is my CSS for t ...