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

Unsuccessful execution of JavaScript in returned HTML after being appended with jQuery .load() or .ajax()

I have attempted to use .load() and $.ajax in order to retrieve some HTML that needs to be added to a specific container. However, the JavaScript enclosed within the fetched HTML is not executing when I add it to an element. When employing .load(): $(&ap ...

Generate a request to load JSON data

On my webpage, I have several external JSON files that need to be loaded. I'm looking for a way to specify the order in which they should be loaded. Using JavaScript for this task, here is an example: const func1 = () => { $.getJSON(json1, re ...

How can I improve the smoothness of my CSS transition when resizing background images?

I'm currently working on creating an intro movie for a game and I thought it would be interesting to use CSS animations. However, I've noticed that some parts of the animation appear bumpy and inconsistent. It seems that depending on the transiti ...

Is it possible to define the sequence of wrapped items in CSS flexbox?

I am using a <div> with CSS flex to maintain responsiveness. I want to control the order in which elements are wrapped. For instance, I need 1 - 2 - 3 To be rearranged as 1 3 2 Once fully wrapped. Here is my current code: https://jsfiddle.net/ ...

Issue with Bootstrap 5 button group not triggering JavaScript events

Is it just me, or does it look like the button group in Bootstrap 5 no longer triggers an event on click or change? How would you go about detecting a change in JavaScript now? In Bootstrap 3, we used $('.btn-group').on('change', ...). ...

What methods can I use to transfer data from one domain to another domain utilizing Ajax JSONP?

Example: The URL of my site is "http://localhost:54887/CustomOrdering.html", but I want to retrieve data from another site "http://localhost:27746/Orders.aspx". In order to do this, I have implemented the following code in my CustomOrdering.html: function ...

Creating a responsive design using Bootstrap4

Today, I made the switch to bootstrap4 and enabled flexbox in _variables.scss. However, I'm still confused about the flexbox capabilities of bootstrap4. Some questions I have include: How can I utilize flex-direction:column? Is it possible to creat ...

Button styles that have been verified will not be shown in Firefox

Hello, first time poster here! Client specifications for CSS: button { border: 1px solid #B8B7B8; border-radius: 8px; height: 4em; margin: 25px 2px 25px 0; text-align: center; text-decoration: none; width: 4em; } button:active, button:che ...

Fetching third-party data and attaching it

I'm having an issue with loading text from an external file, trying to append it and then passing it to a div container but the append function is not working $.get('gallery-lightbox.html', function (data) { var lb_content = data; $ ...

Tips for rendering the stencil as invisible and disabled while still allowing other features (such as rotating and flipping) to remain enabled within the react-advanced-cropper

I am facing a challenge where I need to hide and disable the stencil and overlay in react-advanced-cropper, while keeping all other features like rotation and flipping enabled. Is there a specific property in this library that allows me to disable the st ...

Using a single identifier for multiple functions or event handlers

Just a quick question: is there an alternative method to streamline this code? $('.icMenu span.menu').each(function() { // perform a certain action }); $('.icMenu span.menu').click(function() { // perform a different action } ...

Material UI button component does not have the applied class

I'm encountering an issue with applying a CSS class (redirectButton) to a Material UI button. Despite my efforts, the class is not being successfully applied. Below is the HTML code in question: {(isDataAdapterAdmin && !dataSources?.length) & ...

connect to new database using mysqli_find_cat

<?php $host = "localhost"; $username = "root"; $password = ""; $db = "mineforums"; $connect = mysqli_connect($host, $username, $password, $db) or die(mysqli_error($connect)); ?> Here is the PHP snippet that connects to my databa ...

Create a CSV document using information from a JSON dataset

My main goal is to create a CSV file from the JSON object retrieved through an Ajax request, The JSON data I receive represents all the entries from a form : https://i.sstatic.net/4fwh2.png I already have a working solution for extracting one field valu ...

"Null" is the value assigned to a JavaScript variable

I am encountering an issue on line 30 with the $.each(data.menu, function (). The console is indicating that "data is null". Can someone clarify what's happening? Thank you! function getFoodMenuData () { var url = 'http://localhost:88 ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

Posting Form Data with Ajax in CodeIgniter

Incorporating the CodeIgniter framework along with the jQuery Form plugin available at http://malsup.com/jquery/form/ Encountering challenges in ensuring proper functionality of a form. View <div class="row"> <div class="well c ...

Creating a personalized input slider: A step-by-step guide

I have a question about how to design a custom input slider with the label inside the field itself. The desired output should look like the screenshot below: I have successfully created the input field part, but I am struggling with adding the label and ...

Creating clickable data columns in jQuery DataTablesWould you like to turn a column in your

How can I turn a column into a clickable hyperlink in a jQuery DataTable? Below is an example of my table structure: <thead> <tr> <th>Region</th> <th>City</th> <th> ...

applying different styles to various elements

As a newcomer to the world of jQuery, I am attempting to achieve the following goal: I have several instances of a div, and for each instance, I randomly assign a class from a predefined list in order to modify certain attributes. While this process is su ...