Using CSS3 Transitions, Transforms and Animation

Demo 2 - One image to another, when a button is pressed (transitions)

Plan

Same as before, but instead of using the :hover pseudo class, we are going to use javascript to add a toggle a class. I'm using jQuery here because it's easy to understand, though you could just use plain old JS.

Demo

Click me to toggle

Code

First up, the HTML markup. Again, with no CSS enabled, you just get two images.

<div id="cf2" class="shadow">
	<img class="bottom" src="/tests/images/Stones.jpg" />
	<img class="top" src="/tests/images/Summit.jpg" />
</div>
<p id="cf_onclick">Click me to toggle</p>

Then the CSS. I've added a class with the opacity value.

#cf2 {
	position:relative;
	height:281px;
	width:450px;
	margin:0 auto;
}
#cf2 img {
	position:absolute;
	left:0;
	-webkit-transition: opacity 1s ease-in-out;
	-moz-transition: opacity 1s ease-in-out;
	-o-transition: opacity 1s ease-in-out;
	-ms-transition: opacity 1s ease-in-out;	
	transition: opacity 1s ease-in-out;
}

#cf2 img.transparent {
	opacity:0;
}
#cf_onclick {
	cursor:pointer;
}			

Then the extremely short JS. Note that the browser is smart enough to realise that it can animate to the new properties, I didn't have to set them in javascript (thought that works too).

$(document).ready(function() {
	$("#cf_onclick").click(function() {
		$("#cf2 img.top").toggleClass("transparent");
	});
});			

Have a look at the multiple image demo to see how to extend this idea to more than two images.

Comments/Questions?

Please add any questions/corrections/extra info below. Please be courteous to other users.

blog comments powered by Disqus

Contents

The whole thing on one page
  1. How to use transitions
  2. How to use transforms
  3. How to use animations
  4. Cross fading images
    1. On hover
    2. On button press
    3. With timer
    4. More than just fades
    5. Animating the background-image property
  5. Sliding content
    1. Sliding by transitions
    2. Sliding by transitions + translations
  6. 3D Flipping content
  7. Animated Accordions
  8. Notes on browser support
  9. How will it look in legacy browsers?
  10. Further Reading
Fork me on GitHub