Initiate an animation as you scroll down

How can I create an animation that transitions from color to grayscale, triggered only when the user scrolls down? This is necessary because my website contains numerous images that require scrolling to reach.

Check out the fiddle example here: http://jsfiddle.net/4tHWg/7/

 .box {
       float: left;
       position: relative;
       width: 14.285714286%;



    }

    .boxInner img {
       width: 100%;
       display: block;

    }

    .boxInner img:hover {
      -webkit-filter: grayscale(0%);
    }

@-webkit-keyframes toGrayScale {
    to {
        -webkit-filter: grayscale(100%);
    }
}

.box:nth-child(1) img {
    -webkit-animation: toGrayScale 1s 0.5s forwards;
}

.box:nth-child(2) img {
    -webkit-animation: toGrayScale 2s 1s forwards;
}

.box:nth-child(3) img {
    -webkit-animation: toGrayScale 3s 1.5s forwards;
}

Answer №1

Give this a try!

$( window ).scroll(function() {
    $(".box").each(function (index){
        if (index == 1)
        {
            $(":nth-child("+index+")", $(this)).css('-webkit-animation','toGrayScale 1s 0.5s forwards');
        }
        if (index == 2)
        {
            $(":nth-child("+index+")", $(this)).css('-webkit-animation','toGrayScale 2s 1s forwards');
        }
        if (index == 2)
        {
            $(":nth-child("+index+")", $(this)).css('-webkit-animation','toGrayScale 3s 1.5s forwards');
        }
    });

Answer №2

If my understanding is correct about your objective, you can manage scrolling using the .scroll() function. This will activate the animation when the window's .scrollTop() hits the offset().top of each .box.

$(window).scroll(function(){
    var st = $(this).scrollTop();

    $('.box').each(function(index, element){
        if(st >= $(this).offset().top){
            $(this).find('img').css({'-webkit-animation':'toGrayScale 1s 1s forwards'});
        }
    });
});

Check out the revised fiddle.

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

"Navigation Side Menu: w3-sidebar with hamburger toggle feature

If you are looking to implement the w3-sidebar, you can find it here: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_sidebar_over The existing code uses a "hanburger" icon to open the side menu and a "Close X" menu item to close it. To simpl ...

Do API applications require a session to function properly?

I am in the process of developing an API and I am unsure whether I should implement express-session or a similar tool to handle sessions. app.use(expressSession({ secret: 'Something' }); Moreover, I have been blocking CORS. Is this measure suf ...

What is the best way to incorporate messages across various channels with a Discord bot?

While browsing through the questions of other users, I stumbled upon exactly what I was looking for. My dilemma now is how to make the same bot perform similar tasks on various channels but with different titles, footers, and so on... The primary code sni ...

Guide to writing a Jasmine test case to verify Toggle class behavior within a click event

My directive is responsible for toggling classes on an element, and it's working as expected. However, I seem to be encountering an issue with the jasmine test case for it. // Code for toggling class fileSearch.directive('toggleClass', func ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

The dynamic data is not displaying on the Chart bundle JavaScript

I am currently utilizing chart bundle js for my project. While everything appears to be functioning properly on alter show, I am encountering an issue with the map display – nothing is showing up as intended. If anyone has a solution to resolve this iss ...

How to retrieve an array value within a function in AngularJS

<select class="form-control" id="column" ng-model="selectedcolumn" ng-options="column for column in columns"></select> <input type="text" ng-model="test[selectedcolumn]" ng-change="search()" /> Is there a way to retrieve the value o ...

What is the process for sending a JSON response and then redirecting to an HTML page after a successful event in Node.js using Express?

Trying to send a JSON response and redirect the page simultaneously in Express.js. Need help figuring out how to achieve this. Is it possible to redirect in Express.js while sending a JSON response to the client? The goal is to use this JSON data to render ...

Evaluating CSS Specificity

Is there a recommended approach for automatically testing css selectors? I am in the process of developing a SCSS framework and I want to integrate automated tests. Specifically, I aim to verify that the css selectors are functioning correctly. For examp ...

CSS designed for small-screen laptops is also being utilized on iPads running Safari

To specifically target the iPad/Safari browser and accommodate some minor differences in appearance compared to windows/linux browsers, we are implementing the following HTML meta tag and style query: <meta name="viewport" content="width=device-width, ...

How can AngularJS service methods be assigned to controller $scope for use in an ng-repeat loop in the view?

As part of my development process, I decided to refactor my controller code in order to make it more reusable across multiple controllers. The original version of the controller (colorController.js) worked perfectly fine before I attempted to refactor it i ...

What is the best way to uppercase each element in an array using only a while loop in plain ECMAScript 5?

Struggling with a simple exercise that requires converting names to uppercase and passing them to an empty array using only while loop(s) in plain JavaScript: var names = ['rob', 'dwayne', 'james', 'larry', 'st ...

Issues with Bootstrap Input Group functionality

I am attempting to align multiple form elements in a row, however I am encountering some unusual behavior. My goal is to have the checkbox, label, number input, and select dropdown appear in the same line as shown in this image: https://i.sstatic.net/rARZ ...

Spring's $.getJSON failing to trigger callback functions

After conducting extensive research, I have come across many similar issues but nothing that has provided a solution to my problem. I am facing an issue where my getJSON call is successfully calling my Spring controller and receiving JSON data in response ...

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...

Encountered a SyntaxError stating 'Unable to use import statement outside a module' while attempting to utilize three.js

I'm facing difficulties with incorporating three.js into my project. Initially, I executed: I am referring to the guidelines provided here: In my VS Code terminal for the project folder, I ran the following command: npm install --save three Subsequ ...

Upcoming verification with JSON Web Token

I am looking to incorporate JWT auth into my Next app. Currently, I have mapped out the flow as such: User enters email and password to log in Server responds with status 200 and a jwt access token in httpOnly cookies My main dilemma lies in deciding on ...

Displaying XML data in an HTML table

Encountered a challenge while fetching data from an external XML document using JS. Following the w3schools tutorial for AJAX XML, but faced an issue I couldn't resolve. The XML structure is as follows: <root> <document-id> <author ...

What is the best approach to retrieve a recently upserted document in MongoDB?

When executing the command below, with foos representing a collection, I perform an "upsert" of a new item: foos.update(criteria, { $set: fooUpdate }, { w: 1, upsert: true }, function(err, upsertedFoo) { /* upsertedFoo represents the count of ...

Ways to generate multiple void components side by side using React

What is the most efficient method for creating multiple empty inline elements using React in a declarative manner? Suppose I need 8 empty divs, I tried the following approach but it didn't work. Is there a more effective way? render() { return ( ...