269

Is it possible to use CSS3 transition animation on page load without using Javascript?

This is kind of what I want, but on page load:

image-slider.html

What I found so far

joeljpa
  • 317
  • 2
  • 13
Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • @blesh: almost anything - see, for example, http://www.mysociety.org/2011/08/11/mobile-operators-breaking-content/ and http://robertnyman.com/2006/04/25/an-important-lesson-learned-about-ajax-and-accessibility/ – NickFitz Aug 12 '11 at 10:47
  • 2
    Keyframes will accomplish this and provide the best fallback when CSS3 animations are not supported. Why do you think they're too slow? – zachleat Jul 05 '12 at 21:58
  • 2
    Hi! The link is now broken and I don't know where it was meant to go so can somebody fix it please! – James Ashwood May 10 '20 at 12:26

13 Answers13

579

You can run a CSS animation on page load without using any JavaScript; you just have to use CSS3 Keyframes.

Let's Look at an Example...

Here's a demonstration of a navigation menu sliding into place using CSS3 only:

@keyframes slideInFromLeft {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(0);
  }
}

header {  
  /* This section calls the slideInFromLeft animation we defined above */
  animation: 1s ease-out 0s 1 slideInFromLeft;
  
  background: #333;
  padding: 30px;
}

/* Added for aesthetics */ body {margin: 0;font-family: "Segoe UI", Arial, Helvetica, Sans Serif;} a {text-decoration: none; display: inline-block; margin-right: 10px; color:#fff;}
<header>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="#">Products</a>
  <a href="#">Contact</a>
</header>

Break it down...

The important parts here are the keyframe animation which we call slideInFromLeft...

@keyframes slideInFromLeft {
    0% {
        transform: translateX(-100%);
    }
    100% {
        transform: translateX(0);
    }
}

...which basically says "at the start, the header will be off the left hand edge of the screen by its full width and at the end will be in place".

The second part is calling that slideInFromLeft animation:

animation: 1s ease-out 0s 1 slideInFromLeft;

Above is the shorthand version but here is the verbose version for clarity:

animation-duration: 1s; /* the duration of the animation */
animation-timing-function: ease-out; /* how the animation will behave */
animation-delay: 0s; /* how long to delay the animation from starting */
animation-iteration-count: 1; /* how many times the animation will play */
animation-name: slideInFromLeft; /* the name of the animation we defined above */

You can do all sorts of interesting things, like sliding in content, or drawing attention to areas.

Here's what W3C has to say.

Community
  • 1
  • 1
Chris Spittles
  • 15,023
  • 10
  • 61
  • 85
  • 31
    What makes this run on page load, and not any earlier? – Rolf Dec 30 '13 at 18:21
  • 3
    Just to answer the question above, it appears by default the animation starts 0s after it is applied, with no delay. There is an additional property, animation-delay, that can be set to control this. See: http://www.w3.org/TR/css3-animations/#animation-delay-property – Michael Davis Feb 24 '14 at 00:18
  • 7
    To ensure the animation would begin after the document loads, place the animation code in a stylesheet below the body element or style tag at the bottom of the body element. – TaylorMac Jan 28 '16 at 04:27
  • @SuzanneEdelmanCreoconcept to my knowledge, IE9 doesn't support the transition property. Your options would be JS or graceful degradation. – Chris Spittles Oct 22 '16 at 15:37
  • This is fantastic! Thank you! I would like to note that the `!important` flag in your `@keyframes` will be ignored and may have unexpected behavior. Check [here](https://developer.mozilla.org/en-US/docs/Web/CSS/@keyframes) for more info. For example, I wanted to transition the width on a horizontal bar chart. The width on the bars are set as inline styles, so I wanted `width: 0px !important` at `0%`. I instead used `transform: translateX (-100%);` at `0%` and `transform: translateX (0%);` at `100%` with `overflow:hidden` on the parent element. – WebWanderer Dec 14 '16 at 23:05
  • 2
    Excellent answer, has helped me in 2019! – Gosi Jul 25 '19 at 06:32
  • 2
    It's not "onload" but you can delay the start by adding a step to the keyframe and increasing the animation time: @keyframes slideInFromLeft { 0% { transform: translateX(-100%); } 50% { transform: translateX(-100%); } 100% { transform: translateX(0); } } header { /* This section calls the slideInFromLeft animation we defined above */ animation: 10s ease-out 0s 1 slideInFromLeft; background: #333; padding: 30px; } – mHenderson Apr 06 '21 at 20:56
  • Is there a way to load them only on initial page load? – Jujucat Aug 12 '21 at 16:37
39

Very little Javascript is necessary:

window.onload = function() {
    document.body.className += " loaded";
}

Now the CSS:

.fadein {
    opacity: 0;
    -moz-transition: opacity 1.5s;
    -webkit-transition: opacity 1.5s;
    -o-transition: opacity 1.5s;
    transition: opacity 1.5s;
}

body.loaded .fadein {
    opacity: 1;
}

I know the question said "without Javascript", but I think it's worth pointing out that there is an easy solution involving one line of Javascript.

It could even be inline Javascript, something like that:

<body onload="document.body.className += ' loaded';" class="fadein">

That's all the JavaScript that's needed.

Rolf
  • 5,550
  • 5
  • 41
  • 61
  • 2
    A little Fix: – Ivan Pirog Nov 16 '13 at 12:39
  • 1
    If no need to wait the page onLoad event insert this code before

    tag:

    – Ivan Pirog Nov 16 '13 at 12:52
  • Thanx for the fix, Ivan! I fixed it in my post. Strange, I though this would point to the body element. – Rolf Nov 19 '13 at 01:17
  • 9
    To avoid the override of existing `body` classes use: `document.body.classList.add('loaded)` – Vyacheslav Cotruta Sep 12 '15 at 19:16
  • 1
    I found `document.body.className += " loaded";` to be slightly less verbose for _adding_ the `loaded` class to existing classes. – Pim Schaaf Apr 26 '16 at 04:42
  • 1
    @PimSchaaf Thanks for your suggestion, it totally makes sense. I'll edit it now. Nowadays you can also use classList which is a little more elegant (but less compatible). – Rolf Apr 26 '16 at 17:52
26

I think I have found a sort of work around for the OP question - instead of a transition beginning 'on.load' of the page - I found that using an animation for an opacity fade in had the same effect, (I was looking for the same thing as OP).

So I wanted to have the body text fade in from white(same as site background) to black text colour on page load - and I've only been coding since Monday so I was looking for an 'on.load' style thing code, but don't know JS yet - so here is my code that worked well for me.

#main p {
  animation: fadein 2s;
}
@keyframes fadein {
  from { opacity: 0}
  to   { opacity: 1}
}

And for whatever reason, this doesn't work for .class only #id's(at least not on mine)

Hope this helps - as I know this site helps me a lot!

TheNuggitMan
  • 400
  • 3
  • 5
9

CSS only with a delay of 3s

a few points to take here:

  • multiple animations in one call
  • we create a wait animation that just delays the actual one (the second one in our case).

Code:

header {
    animation: 3s ease-out 0s 1 wait, 0.21s ease-out 3s 1 slideInFromBottom;
}

@keyframes wait {
    from { transform: translateY(20px); }
    to { transform: translateY(20px); }
}

@keyframes slideInFromBottom {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}
Claudiu
  • 3,700
  • 1
  • 38
  • 35
6

Well, this is a tricky one.

The answer is "not really".

CSS isn't a functional layer. It doesn't have any awareness of what happens or when. It's used simply to add a presentational layer to different "flags" (classes, ids, states).

By default, CSS/DOM does not provide any kind of "on load" state for CSS to use. If you wanted/were able to use JavaScript, you'd allocate a class to body or something to activate some CSS.

That being said, you can create a hack for that. I'll give an example here, but it may or may not be applicable to your situation.

We're operating on the assumption that "close" is "good enough":

<html>
<head>
<!-- Reference your CSS here... -->
</head>
<body>
    <!-- A whole bunch of HTML here... -->
    <div class="onLoad">OMG, I've loaded !</div>
</body>
</html>

Here's an excerpt of our CSS stylesheet:

.onLoad
{
    -webkit-animation:bounceIn 2s;
}

We're also on the assumption that modern browsers render progressively, so our last element will render last, and so this CSS will be activated last.

dodov
  • 5,206
  • 3
  • 34
  • 65
foxy
  • 7,599
  • 2
  • 30
  • 34
3

Even simplier solution (still with [one line inline] javascript):

Use this as the body tag: Note that body. or this. did not work for me. Only the long ; querySelector allow the use of classList.remove (Linux Chromium)

<body class="onload" onload="document.querySelector('body').classList.remove('onload')">

and add this line on top of your other css rules.

body.onload *{ transform: none !important; }

Take note that this can apply to opacity (as requested by OP [other posters] ) simply by using opacity as a transition trigger instead. (might even work on any other css ruling in the same fashion and you can use multiple class for explicity delay between triggering)

The logic is the same. Enforce no transform (with :none !importanton all child element of body.onloadand once the document is loaded remove the class to trigger all transition on all elements as specified in your css.

FIRST ANSWER BELOW (SEE EDIT ABOVE FOR SHORTER ANSWER)

Here is a reverse solution:

  1. Make your html layout and set the css accordingly to your final result (with all the transformation you want).
  2. Set the transition property to your liking
  3. add a class (eg: waitload) to the elements you want to transform AFTER load. The CSS keyword !important is the key word here.
  4. Once the document is loaded, use JS to remove the class from the elements to to start transformation (and remove the transition: none override).

Works with multiple transition on multiple elements. Did not try cross-browser compatibility.

div {
  width: fit-content;
}

#rotated {
  transform: rotate(-50deg)/* any other transformation */
  ;
  transition: 6s;
}

#translated {
  transform: translate(90px)/* any other transformation */
  ;
  transition: 6s;
}

.waitload {
  transform: none !important;
}
<div id='rotated' class='waitload'>
  rotate after load
</div>
<div id='translated' class='waitload'>
  trasnlate after load
</div>
<script type="text/javascript">
  document.addEventListener('DOMContentLoaded', init);

  function init() {
    [...document.querySelectorAll('.waitload')]
    .map(e => e.classList.remove('waitload'));
  }
</script>
the Hutt
  • 16,980
  • 2
  • 14
  • 44
Louis Loudog Trottier
  • 1,367
  • 13
  • 26
2

add this to your css for fade in animation

body{animation: 2s ease-out 0s 1 FadeIn;}
@keyframes FadeIn {
    0% {
      opacity:0;
    }
    100% {
      opacity:1;
    }
}

increase the ease-out time if you want it to load slower

Alan Yong
  • 993
  • 2
  • 12
  • 25
1

Similar to @Rolf's solution, but skip reference to external functions or playing with class. If opacity is to remain fixed to 1 once loaded, simply use inline script to directly change opacity via style. For example

<body class="fadein" onload="this.style.opacity=1">

where CSS sytle "fadein" is defined per @Rolf,defining transition and setting opacity to initial state (i.e. 0)

the only catch is that this does not work with SPAN or DIV elements, since they do not have working onload event

1

start it with hover of body than It will start when the mouse first moves on the screen, which is mostly within a second after arrival, the problem here is that it will reverse when out of the screen.

html:hover #animateelementid, body:hover #animateelementid {rotate ....}

thats the best thing I can think of: http://jsfiddle.net/faVLX/

fullscreen: http://jsfiddle.net/faVLX/embedded/result/

Edit see comments below:
This will not work on any touchscreen device because there is no hover, so the user won't see the content unless they tap it. – Rich Bradshaw

isherwood
  • 58,414
  • 16
  • 114
  • 157
beardhatcode
  • 4,533
  • 1
  • 16
  • 29
0

Ok I have managed to achieve an animation when the page loads using only css transitions (sort of!):

I have created 2 css style sheets: the first is how I want the html styled before the animation... and the second is how I want the page to look after the animation has been carried out.

I don't fully understand how I have accomplished this but it only works when the two css files (both in the head of my document) are separated by some javascript as follows.

I have tested this with Firefox, safari and opera. Sometimes the animation works, sometimes it skips straight to the second css file and sometimes the page appears to be loading but nothing is displayed (perhaps it is just me?)

<link media="screen,projection" type="text/css" href="first-css-file.css"  rel="stylesheet" />

<script language="javascript" type="text/javascript" src="../js/jQuery JavaScript Library v1.3.2.js"></script>

<script type='text/javascript'>
$(document).ready(function(){

// iOS Hover Event Class Fix
if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) ||
(navigator.userAgent.match(/iPad/i))) {
$(".container .menu-text").click(function(){  // Update class to point at the head of the list
});
}
});
</script>

<link media="screen,projection" type="text/css" href="second-css-file.css"  rel="stylesheet" />

Here is a link to my work-in-progress website: http://www.hankins-design.co.uk/beta2/test/index.html

Maybe I'm wrong but I thought browsers that do not support css transitions should not have any issues as they should skip straight to the second css file without delay or duration.

I am interested to know views on how search engine friendly this method is. With my black hat on I suppose I could fill a page with keywords and apply a 9999s delay on its opacity.

I would be interested to know how search engines deal with the transition-delay attribute and whether, using the method above, they would even see the links and information on the page.

More importantly I would really like to know why this is not consistent each time the page loads and how I can rectify this!

I hope this can generate some views and opinions if nothing else!

Michael Walkling
  • 197
  • 1
  • 2
  • 11
  • I suspect the reason it worked at all (when it worked) is that there was a delay (caused mostly by waiting for the network) between loading the 1st and 2nd stylesheets. As the page (and associated resources) no longer exists, it's rather hard to test. – outis Dec 18 '20 at 23:50
0

If anyone else had problems doing two transitions at once, here's what I did. I needed text to come from top to bottom on page load.

HTML

<body class="existing-class-name" onload="document.body.classList.add('loaded')">

HTML

<div class="image-wrapper">
    <img src="db-image.jpg" alt="db-image-name">
    <span class="text-over-image">DB text</span>
</div>

CSS

.text-over-image {
    position: absolute;
    background-color: rgba(110, 186, 115, 0.8);
    color: #eee;
    left: 0;
    width: 100%;
    padding: 10px;
    opacity: 0;
    bottom: 100%;
    -webkit-transition: opacity 2s, bottom 2s;
    -moz-transition: opacity 2s, bottom 2s;
    -o-transition: opacity 2s, bottom 2s;
    transition: opacity 2s, bottom 2s;
}

body.loaded .text-over-image {
    bottom: 0;
    opacity: 1;
}

Don't know why I kept trying to use 2 transition declarations in 1 selector and (not really) thinking it would use both.

s3c
  • 1,481
  • 19
  • 28
0

You could use custom css classes (className) instead of the css tag too. No need for an external package.

import React, { useState, useEffect } from 'react';
import { css } from '@emotion/css'

const Hello = (props) => {
    const [loaded, setLoaded] = useState(false);

    useEffect(() => {
        // For load
        setTimeout(function () {
            setLoaded(true);
        }, 50); // Browser needs some time to change to unload state/style

        // For unload
        return () => {
            setLoaded(false);
        };
    }, [props.someTrigger]); // Set your trigger

    return (
        <div
            css={[
                css`
                    opacity: 0;
                    transition: opacity 0s;
                `,
                loaded &&
                    css`
                        transition: opacity 2s;
                        opacity: 1;
                    `,
            ]}
        >
            hello
        </div>
    );
};
Xairoo
  • 335
  • 1
  • 9
  • 1
    I think installing React for triggering an animation on page load is a bit of an overkill. – Marten Apr 20 '22 at 14:01
-2

Not really, as CSS is applied as soon as possible, but the elements might not be drawn yet. You could guess a delay of 1 or 2 seconds, but this won't look right for most people, depending on the speed of their internet.

In addition, if you want to fade something in for instance, it would require CSS that hides the content to be delivered. If the user doesn't have CSS3 transitions then they would never see it.

I'd recommend using jQuery (for ease of use + you may wish to add animation for other UAs) and some JS like this:

$(document).ready(function() {
    $('#id_to_fade_in')
        .css({"opacity":0})   // Set to 0 as soon as possible – may result in flicker, but it's not hidden for users with no JS (Googlebot for instance!)
        .delay(200)           // Wait for a bit so the user notices it fade in
        .css({"opacity":1});  // Fade it back in. Swap css for animate in legacy browsers if required.
});

Along with the transitions added in the CSS. This has the advantage of easily allowing the use of animate instead of the second CSS in legacy browsers if required.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
  • 17
    Why was this answer accepted? It doesn't really do anything that the question asked for. It simply (and very quickly, sometimes unnoticeably) starts the element invisible, waits the small fraction of a second (200 ms) then instantaneously renders it visible again. That's not a fade, last I checked. – VoidKing Nov 26 '12 at 22:59
  • You would include a css transition on the `#id_to_fade in`, though I agree, that's not that clear from the answer. – Rich Bradshaw Nov 27 '12 at 08:34
  • as in, add another .css({transition: 'opacity 2s'}) to the jQuery call? Or just in your css? I have the feeling that I'm gonna feel like this is a stupid question... – VoidKing Nov 28 '12 at 19:40
  • 3
    It's OK – I should have put up a demo really. In CSS, `#id_to_fade_in { -webkit-transition:opacity 0.5s ease-in-out; }` + `-o-`,`-moz-` prefixes as well. – Rich Bradshaw Nov 29 '12 at 08:37
  • 2
    This shouldn't be the accepted answer, using key-frames is the way to go. – Eduardo Naveda Oct 08 '14 at 18:26
  • He said he wouldn't use Key-Frames though, @Chris Spittles solution is the best way to go here. – MaximeBernard Dec 17 '14 at 11:19
  • It's worth noting that I answered this in 2011, when things weren't where they are now - keyframes were badly supported and often had poor framerates and at that point no one had produced a demo where there wasn't a fouc. – Rich Bradshaw Dec 17 '14 at 15:22