Adjust the horizontal background-position transition for color change while scrolling using jQuery and CSS

I came across a fascinating website - - where the background-position changes on scroll() from a linear gradient with two colors to smoothly slide one color off the screen. While I grasped how they achieved the split colors using linear-gradient, I'm struggling to understand the animation effect where the red color seems to 'push' the white color horizontally off the screen.

Here is an attempt I made recently. My ultimate goal is to implement this on scroll, but for now, I'm testing it on click. I've included a hover style for testing purposes as well.

$(document).ready(function() {
  $("button").click(function() {
    $(".box").css('background-position': 'left');
  });
});
.box {
  width: 100px;
  height: 100px;
  display: inline-block;
  background-size: 200% 200%;
  transition: background-position 1s;
  background-image: linear-gradient(to right, blue 50%, green 0);
  background-position: right;
}

.box:hover {
  background-position: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="box"></div>
<br>
<button>Toggle background position</button>

Answer №1

After checking out the link you provided, it seems like using a Scroll event is what you are aiming for.

To start off, we can utilize $(document).ready() or $(window).on('load',.. to kickstart the initial animation by targeting the class .intro.


Subsequently, based on the scroll direction, we switch between two classes: .slideleft and .slideright. If those class names seem confusing, they could also be named Up and Down accordingly.

$(document).ready(function() {
  $('.box').addClass('intro');
});
(function() {
  var lastScroll = 0;
  $(window).on('scroll', function() {
    if ($(".box").is(".intro")) {
      $('.box').removeClass('intro');
    }
    var activeScroll = $(this).scrollTop();
    //Check the scroll direction
    cond = Boolean(activeScroll > lastScroll);
    //Apply background slide effect based on scroll direction
    $(".box").toggleClass('slideleft', cond); //DownScroll
    $(".box").toggleClass('slideright', !cond); //UpScroll
    lastScroll = activeScroll;
  });
}());
.box {
  width: 100%;
  height: 200px;
  display: inline-block;
  background-size: 200% 200%;
  transition: background-position 1s;
  background-image: linear-gradient(to right, #ff5851 50%, #F8F8F8 50%);
  background-position: left;
}

.intro {
  background-position: 50%;
}

.slideleft {
  background-position: left center;
}

.slideright {
  background-position: center center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<div class="lorem">
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
  <p>Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum</p>
</div>

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 keep encountering an issue with getJson

A snippet of my JavaScript code retrieves a JSON object from a URL. Here is the portion of the code in question: <script> $(document).ready(function(){ $("button").click(function(){ $.getJSON('url_address', {}, function(data) { ...

How can jQuery be used to effectively remove the first nested div within another div element?

Here is a sample markup: <div id="parent"> <div id="divToRemove"> </div> </div> The following jQuery code can be used to remove the first div element: $('#parent').find('div').remove(); Is this the mo ...

The server's request is being processed through jQuery's ajax functionality

Recently, I've started working with jQuery and AJAX. Essentially, the webpage sends an HTTP post request, and the server-side DLL responds by writing a JSON-formatted response back to the page. I'm trying to understand how to handle this response ...

Attempting to create a JavaScript function that will show a JSON array when the next button is clicked

I am facing an issue with displaying a JSON array based on specific start and end indices. Even though I managed to display the entire array, the first button click does not seem to work as expected. Upon clicking the first button, an error message "this.d ...

JQuery UI button causing an error in Internet Explorer related to "potentially harmful Request.Form value"

While testing my application with Internet Explorer, I discovered that buttons styled with JQuery UI button are sending their entire content to the server. This causes a "A potentially dangerous Request.Form value was detected from the client" error in ASP ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...

Attempting to replicate the functionality of double buffering using JavaScript

In my HTML project, I have a complex element that resembles a calendar, with numerous nested divs. I need to refresh this view in the background whenever there are updates on the server. To achieve this, I set up an EventSource to check for data changes on ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

Center a grid of cards on the page while keeping them aligned to the left

I have a grid of cards that I need to align in the center of the page and left within the grid, adjusting responsively to different screen sizes. For example, if there are 10 cards and only 4 can fit on a row due to screen size constraints, the first two ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

Sorting rows by words and numbers in JavaScript explained

Hello, I'm a beginner and I need help sorting the table rows in the following table. I also want to attach an onclick listener to the header after it is displayed. ID Name Inventory Volume 1 Rachel Data is not enough 2 Ross 100 3 Monica 1 ...

Troubleshooting problem with CSS background image

I'm looking to make my webpage more dynamic and interactive. One issue I have is that the background image of the body element stretches when new elements are added, which is not the desired behavior. Any suggestions on how I can fix this? <styl ...

Setting a one-month date range in Bootstrap Material date picker - a simple guide

Is it possible to configure a 1-month date range in the Bootstrap Material date picker? Check out this link for more information ...

The jQuery hide() method conceals an element without affecting its parent

Can't seem to figure out JQuery... So, here's the issue: I've got a page where visitors can enter their email address by clicking on a link inside a div (id="contact"). <div id="contact"><a href="">Interested in leaving your con ...

Avoiding the triggering of jQuery events from child elements

Here is the code snippet I am working with: <html> <head> <script src="http://code.jquery.com/jquery-1.6.2.min.js" type="text/javascript"> </script> </head> <body> <div id=&q ...

Choosing Only the Visible Element with CSS

Within my program, there exists a text element that appears in two distinct sections: section A and section B (in the form of a popup). My intention was to create one object using CSS that could be utilized in both areas. By doing so, I would be able to em ...

Implement functionality in JS to track the number of clicks on an element

I am dealing with a ul-list containing an unpredictable number of li-elements, ranging from 2 to 8. My goal is to capture votes using these li-elements and display the vote count on the specific element that was clicked. I have attempted to catch the click ...

Trick for using :checked in CSS

Is it possible to change the color of a deep linking div using an input checkbox hack in the code below? <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /&g ...

Dynamic height adjustment for Bootstrap right column

I am struggling to create a layout with a right column using bootstrap. I can't figure out how to achieve the desired arrangement shown in this image. https://i.stack.imgur.com/VaIWD.png I have attempted various methods but the right column does not ...

Is it necessary to adjust my font stack for optimal viewing on a high DPI tablet or computer screen?

My CSS includes the following font definition: html { font-size: 95%; font-family: Arial, Helvetica, sans-serif } I want my application to display well on PC, iOS, and Android tablets. I am aware that different devices have varying resolutions. C ...