Thursday, August 22, 2013

Firing CSS3 Transition on Page Load Event (in WordPress)

CSS3 has some pretty cool stuff ~ among these are transitions and animations. So, when I was tasked with making the tagline on my company's website "pop" or stand out somehow, CSS3 is the first thing that came to mind.

It was fairly easy, but the one trick I needed to figure out was how to make it all happen when the page is finished loading -- of course, WordPress didn't really make this easy on me... it has a nasty habit of not rendering or interpreting the code that I tell it to. Naturally.

Anyway, here is the tagline...
(forgive the poor quality of the GIF I used to record the browser window)




Here is the HTML event hook, which I added this to my header.php file...
(don't you just love that WordPress syntax BS?)
<script language="JavaScript" type="text/javascript">
// <![CDATA[
window.onload = function(){
  document.getElementById("body").setAttribute("class","loaded"); }
// ]]>
</script>

And add an ID attribute to the body tag, with a value of "body" for the hook above...
(ignore the elipses, I have other stuff in that tag that you don't need to care about)
<body id="body" ...>

Here is the CSS...
(the tagline container is classed "header-right" ~ the only thing you need to care about is the "#body.loaded" selector)
.header-right div {
  color: #ffffff;
  font-size: 1.8em;
  font-weight: normal;
  text-align: right;
  line-height: 1;
  margin-right: 15px;
  font-style: italic;
  text-shadow: 0 0 0 #dd5500;
  /*the following configures our transition effect - 500/200ms are
    delays to give the page time to render before doing transitions*/
  transition: color 2500ms ease-out 500ms, text-shadow 2000ms ease-in 200ms;
}
#body.loaded .header-right div {
  color: #178582;
  text-shadow: 0 0 180px #ff9944;
}

How does it work? Well, basically, you give the body node (which is what onLoad works with) an ID that we can later use to grab it and work with. Then, a JavaScript listens for the onLoad event; and when it fires, that same JavaScript will apply an attribute (class="loaded") to the body tag. Then, CSS will naturally go in and apply the transition effect (since the selector for "loaded" now exists in the document).

No comments:

Post a Comment