Tips for creating a scrolling animation effect with images

I'm currently attempting to create an animation on an image using HTML/CSS. The issue I'm facing is that the animation triggers upon page load, but I would like it to activate when scrolling down to the image.

Below is my snippet of HTML:

<figure>
   <img src="Assets/Images/klenet.jpg" id="clenet_picture">  
   <figcaption id="clenet_text">Clenet Series 1 from 1979.</figcaption>
</figure>

And this is my CSS section:

#clenet_picture
{
   . . .

   animation-name: image-anim;
   animation-duration: 4s;
}
@keyframes image-anim
{
   from {opacity: 0%}
   to {opacity: 100%}
}

I understand that I need to incorporate some JavaScript to achieve the desired effect, but I'm unsure of how exactly to implement it. Can anyone guide me through that process?

Answer №1

Use JavaScript to add an additional class to the element, such as animate

Now you can target the element with #clenet_picture.animate instead of just #clenet_picture, and the animation will only trigger once the new class is applied

Need to know if an image is within the viewport? Check out this helpful resource: How can I tell if a DOM element is visible in the current viewport?

Answer №2

After some research, I stumbled upon what appears to be a straightforward resolution.

Alas, there is one vexing obstacle standing in the way.

Behold, the code:

const marker = 750;

        window.addEventListener("scroll", () => {
            
            const currentScroll = window.pageYOffset;
            
            if (currentScroll <= marker) {
                transparency = 1 - currentScroll / marker;
            } else {
                transparency = 0;
            }
            
            document.querySelector(".toAnimate").style.opacity = transparency;
        });

The quandary lies in the fact that it now behaves contrarily... When approaching the image while scrolling, its opacity diminishes to 0 and as you move away from it, it fades back to 1...

If anyone can offer a solution, I would greatly appreciate it.

A heartfelt thank you to all those who provide answers!

Answer №3

Success! The issue has been resolved.

Check out the revised code below:

//You determine the checkpoint value
const checkpoint = 550;

window.addEventListener("scroll", () => {
    
    const currentScroll = window.pageYOffset;
    
    let opacity;
    
    if (currentScroll <= checkpoint) {
        opacity = 0 + currentScroll / checkpoint;
    } else {
        opacity = 1;
    }
    
    document.querySelector(".toAnimate").style.opacity = opacity;
});

This straightforward solution works effectively even without CSS!

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

Is it possible to reverse the use of JQuery's .each() function without any additional plugins or modifications?

Similar Question: Reversing JQuery .each() Is there a better approach to using .each() in reverse? Currently, I am implementing it like this: var temp = []; $("#nav a").each(function() { temp.push($(this)); }); temp.reverse(); for(var i = 0; i ...

When attempting to integrate Angular 1.4's new router with components, an issue arises where a warning is triggered stating, "Failed to instantiate controller HeadlinesController

Attempting to work with Angular for the first time and struggling to load a component using data from an http request. Currently encountering a warning when attempting to execute the code with the HTTP request. Receiving a "Could not instantiate control ...

Windows npm configuration settings

After receiving helpful answers to my previous question about using a named parameter in an npm run script, I encountered a new problem. It seems that the $npm_config_variable doesn't function correctly on Windows OS. I am in search of a solution that ...

JQuery method for extracting a specific span's content from a div

I am faced with extracting specific text from a span within a div element. Below is the code snippet for my Div: '<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid ...

What could be causing the image URL to not function properly in the CSS file?

I have been struggling with this issue all day and have searched numerous sources for answers. The login.css file can be found at: WebContent/resources/css/login.css The image file is located here: WebContent/resources/img/pencil.jpg Despite my attem ...

Transferring information between two components in separate Angular 4 modules

Within my application, I have defined two modules named AppModule and UserModule. I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule). Below is a snippet of app.componen ...

The primary content division is trapped behind the side navigation bar

Why is my sidebar fixed on the left of the screen overlapping with the main content? I want the main content to be displayed next to the navbar and scroll up and down while keeping the nav bar in place, but no matter what styling I apply, it doesn't w ...

The Angular directive ng-if does not function properly when trying to evaluate if array[0] is equal to the string value 'Value'

In my code, I want to ensure that the icon is only visible if the value at array index 0 is equal to 'Value': HTML <ion-icon *ngIf="allFamily[0] === 'Value'" class="checkas" name="checkmark"></ion-icon> TS allFamily = [ ...

When attempting to utilize a global variable in a POST request, it may be found to

My dilemma is that I can successfully access the global variable in other requests such as 'GET', but it becomes undefined when used in a 'POST' request. var dirName; app.post("/addFace", function (req, res) { //create directory con ...

tips on utilizing the JSON information transmitted from the backend

$.ajax({ url: '{{ URL('reports/groupsUsersGet') }}', dataType: "json", data: { group_id : $('#group').val(), }, success: function(data) { <li>"i need to insert variable here"</li> }, error: function (data) ...

Using HTML and JavaScript to choose relatives from the extended family: Uncles and Aunts

Looking for a better way to target elements in your HTML code? <div class="chunk" id=""> <div class="chunkContent"> <div class="textLeft" ></div> <div class="textRight" ></div> <div class= ...

After clicking a button in AngularJS, how can you retrieve one of the two JSON files and store it in a $scope variable?

For instance, You have two JSON files: Json file #1: [{colorname:blue},{colorname:blue}] Json file #2: [{colorname:red},{colorname:red}] Within the controller, there exists a variable called $scope.color In the HTML code, there are two buttons named " ...

The Ajax call failed to connect with the matching JSON file

<!DOCTYPE html> <html> <body> <p id="demo"></p> <script <script> function launch_program(){ var xml=new XMLHttpRequest(); var url="student.json"; xml.open("GET", url, true); xml.send(); xml.onreadystatechange=fun ...

Chrome Automatically Playing WebRTC Audio

My webapp has webrtc functionality, but I've noticed a strange issue. When connections are established between Chrome browsers, the audio is not played, while video is. However, this problem doesn't occur with Mozilla users. So... Chrome user 1 ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...

Leveraging the power of jQuery to capture and recycle a dynamically generated date

Using a jQuery plugin, a list of dates is generated. Implementing moment.js works perfectly fine as shown in this fiddle (http://jsfiddle.net/UJ9z4/). However, when attempting to apply it to the live file with the plugin running, an undefined error is enc ...

Tips for optimizing Firestore database requests on the web to minimize the number of API calls

On my product page, every time a user presses F5, the entire list of products gets loaded again. I am looking for a way to save this data locally so that it only needs to be updated once when a new product is added, instead of making multiple API calls. ...

Searching through a JSON object for nested objects within objects

Currently, I have some data structured as follows: var items = [ { "id" : 1, "title" : "this", "groups" : [ {"id" : 1, "name" : "groupA"}, {"id" : 2, "name" : "groupB"} ] }, { "id" : 2, "title" : "that", ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

Placing 2 elements next to each other - Where the left element remains static and the right element's width increases as the page expands

Hey there! I'm really struggling to position two elements, an aside and a section (I believe the use of these HTML5 elements is important for their content). On this page Click Here, my goal is to keep the 'Locations' (Aside) element static ...