Using CSS for a fade-in effect on page load
#1
I'm having trouble getting a CSS fade-in effect to work on page load. I've seen it on a few websites and I'd like to implement it on my own project. The effect should make a text paragraph smoothly transition from invisible to fully visible when the page is loaded. I've set up the initial CSS to make the text element invisible and I've applied a transition rule to it aiming for that fade-in effect. However, I'm not certain how to properly trigger this transition on page load. Here's the current CSS I'm working with:

Code:
#test p {
    opacity: 0;
    margin - top: 25 px;
    font - size: 21 px;
    text - align: center; -
    webkit - transition: opacity 2 s ease - in; -
    moz - transition: opacity 2 s ease - in; -
    o - transition: opacity 2 s ease - in; -
    ms - transition: opacity 2 s ease - in;
    transition: opacity 2 s ease - in;
}

And here's the basic HTML markup:

Code:
<div id = "test" >
    <p > This is a test < /p>
</div>

Any advice on how to get this transition to trigger as soon as the page is done loading would be appreciated.
Reply
#2
To have your fade-in effect on page load, you need to set the final state of your element after the page has loaded. Since you want to trigger a transition, we will need to change the opacity from 0 to 1. This can be done using a small snippet of JavaScript that adds a class to your paragraph once the window's 'load' event fires. Here's how you can do it:
First, add a new class `.fade-in` to your CSS:

Code:
.fade - in {
    opacity: 1;
}

Then, add this JavaScript code:

Code:
});

Now, when the DOM is fully loaded, the JavaScript will execute, adding the `fade-in` class to your paragraph and triggering the CSS opacity transition.
Reply
#3
I see. So the JavaScript will trigger the transition as soon as the DOM is finished loading. However, your code is waiting for `DOMContentLoaded`, not the `window` load event. Is there a reason for that distinction?
Reply
#4
Good catch. The `DOMContentLoaded` event fires when the initial HTML document has been fully loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. The `window` load event, however, waits for the whole page to load. In this case, using `DOMContentLoaded` should be sufficient to trigger the fade-in effect, but if you want to be sure that all the resources are loaded, you can replace `DOMContentLoaded` with the `load` event like this:

Code:
});

Here's your updated, properly formatted CSS and JavaScript, ready to use:
CSS:

Code:
#test p {
    opacity: 0;
    margin - top: 25 px;
    font - size: 21 px;
    text - align: center;
    transition: opacity 2 s ease - in;
}
.fade - in {
    opacity: 1;
}

JavaScript:

Code:
});

This snippet should go within a script tag before the closing body tag in your HTML or in an external file that you link to your HTML.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)