CSS3 – Animating the DOM – Part 2

Have a look at this JSFiddle to see what we will be creating in this section JS Fiddle with all 4 effects. So last post (see here) we spoke about basic transitions using ease-in-out. In this post we will look at other transitions, transitional properties and maybe some transformations too.

Last time we used ease-in-out to create some basic transformations using the opacity levels of an image to fade it out. Lets start by looking at other kinds of basic transitions available to use.

Basic Transitions

ease-in-out is considered a timing function this states how the animation will play out. Here are some other stock functions you can play with.

  • ease – steady pace of animation
  • ease-in  – slowly build up
  • ease-out – start fast and slow towards the end
  • ease-in-out – slowly build up and slowly come to end
  • linear – same momentum throughout time

You can use these timing functions to modify the execution of your animation based on the time you have specified. Playing around with these alone allows you to create animations and interactivity that most websites today cant offer. You can however build more advanced timing functions using this tool Ceaser Transition Creator however use advanced animations with caution.

TIP – Avoid Motion Sickness in your app.

A tip I have found useful when creating web apps. Once you are comfortable with animation in CSS/HTML the overwhelming urge is to animate everything in your application. You start to look at the static DOM elements as boring because they have no life or activity. Depending on the context of your application start by picking one element that you think “That would be really cool if that moved like this when I done this … that would be impressive”. Take that element and animate it, spend time getting the animation fluid and in keeping with the app i.e no photoshop style sliding text with car engines sounding as it speeds across the screen. If you do this you will find clients and users of your application will notice that one singular animation, and it stands out rather than drowned in a sea of flying divs.

I hope this section has covered the basic concept around transitions and how they work. I could have went into more detail around timings and delays but feel they are pretty self explanatory if there are any gaps let me know im happy to add some detail in. To see a list of all properties that can be animated look here

Transforms

So now you should be comfortable with transitions lets add some transformations to the mix. There are commonly 2 type of transforms 2D and 3D lets start with 2D.

4 Examples of 2D transforms

Skew

Code:

#div1 {
margin:100px;
height:100px;
width:100px;
transition:all 1s ease-in;
perspective: 400px;
perspective-origin: 50% 100px;
background:red;
color:white;
}
#div1:hover {
-webkit-transform:skew(180deg);
}

Result

Skew a square with CSS
Skew a square with CSS

Rotate

Code: change the hover code to match below

#div1:hover {
-webkit-transform:rotate(180deg);
}

css3-rotate

Scale

Code: change the hover code to match below

#div1:hover {
-webkit-transform:scale(180deg);
}

The following link will show all 3 effects in action with code side by side

http://jsfiddle.net/cmac458/FraRU/2/

Hopefully this give you an insight into how to add transforms to you html elements and you can now link these to the transitions as explained in part 1 to create some interesting layouts and effects.

CSS3 – Animating the DOM – Part 1

So recently my focus has moved visibly from native mobile development to web based development, this is mainly due to the constrain of work. As I try to keep my blog up to date it only makes sense that I transition the blog to this area too. No doubt I will be back to mobile soon but for now it’s web stuff and today its CSS3.

So recently I wanted to animate some elements of my web application to add a little more interaction to the application. Traditionally animation has been saved for flash websites and flex RIAs. As HTML5 gains steam so will the users expectations of web experiences so we must adapt to create intelligent and engaging applications and using animations can really give an application the feeling that its a living thing and not just a static page.

CSS 3 Basics

We will start with the basics as always and hopefully build up to some more advance techniques in future posts, However you may find that these basic effects can achieve exactly what you need.

Transitions

If you aren’t familiar with transitions then this brief introduction may help. Transitions basically define the start and end of your animation i.e Moving an object from A -> B should take x amount of seconds. You need transitions to make the movement that appears on screen appear seamless and smooth otherwise you will get a stickato movement that looks horrible.

transition: all 1s ease-in-out;

The above CSS follows this format

You can declare each of the above transition properties in its own CSS rule:

transition-property: background-color,width,height;
transition-duration: 2s, 1s, 0.5s;
transition-delay: 0s, 0.5s, 1s;

So this will animate background-color for a duration of 2 seconds and delay of 0s, width for a duration of 1 seconds with a delay of 0.5.

Using the above method you can achieve effects like this

Css3 Transition Opacity on Hover
Css3 Transition Opacity on Hover

You can transition many properties on elements such as color/background/height/ width and so much more you can also combine these to make nice effects too. The above shows how you can use transitions to fade out an image using the Opacity css property.

.div {
background:url(http://imgurl.com);
transition:all 3s ease;
}

.div:hover {
opacity:0;
}

Have a play around with transitions for now and see what effects you can create with using these basic transitions alone, In the next post we will look at more advance transitions and start to take a look at adding transformations on top too.

Touch Events HTML5 – Drag n Drop (DART)

My last post focused on my simple app PicsAPuzzle which can be viewed here (picture below)

PicsAPuzzle
Iteration 1 of PicsAPuzzle

The purpose of the app was a quick learning project for me become more comfortable with Dart. The biggest criticism I had with the project was that I couldn’t play it on my mobile device or iPad. This entered me into find out how to add interactivity via touch events to the html web app.

HTML5 Touch Events 

The HTML5 specification may be huge and still growing but there is a lot of handy features that you may not know exist. Touch Events are one. I wanted to implement Drag and Drop the same way I could with a mouse but using my finger instead. HTML offers onDrag and onDrop event handlers for this. However with touch these do not exist. The three basic touch events are

  • touchStart
  • touchEnd
  • touchMove

There are more such as touchLeave but these 3 are all you need for most tasks. A touch event has 3 list each that contain the number of touches ie fingers on the screen at the time of firing the event.

  • touches
  • targetTouches
  • changedTouches

You set touchEvents the same way as any other kind of event (example in Dart)

tile.on.touchStart.add(_onTouchStart);

Points to consider when using TouchEvents

  1. Zooming – On mobile devices moving multiple fingers about the screen can result in the webpage being zoomed in/out. You may want to prevent this. I recommend doing so for drag n drop operations, You can prevent with following meta tag :
    <meta name="viewport" 
      content="width=device-width, initial-scale=1.0, user-scalable=no">
  2. Scrolling – Especially with Drag n Drop interactions moving your finger around a screen is the default way to scroll a page on mobile devices so using the following code in you handler methods will prevent such interactions with the browser
    event.preventDefault();

Implementing Drag n Drop 

So that covers the basics of touch event’s and how best to prepare your application for mobile devices. We will start looking at implementation of Drag n Drop. Code snippets have been commented to describe the logic without writing addition paragraphs on them.

onTouchStart 

This method works very similarly to the onDragStart/onDragEnter methods. You want to capture the element being dragged and apply some style to the element to indicate to the user that the element is selected and draggable.


void _onTouchStart(TouchEvent event){
//stop scrolling by default
event.preventDefault();
//capture drag target
Element dragTarget = event.target;
//add style to element to indicate its moving
dragTarget.classes.add('moving');
_dragSourceEl = dragTarget;
}

onTouchMove

The event is fired when the finger moves across the screen from its starting co ordinates. Tracking the finger until it stops allows us to simulate the mouse moving across the screen. What I did for this was to capture the co ordinates of the first fingers position and find out which element the finger was over, that way when the finger is removed we know the last place it visited.


void _onTouchMove(TouchEvent event){
//indicate to user element is in motion
_dragSourceEl.classes.add('moving');
//prevent all default behaviour ie Scrolling
event.preventDefault();
//Get the current x,y position of the first finger and find the element it is over
_dropTarget = document.elementFromPoint(event.touches[0].pageX,event.touches[0].pageY);
// If the finger is over an element indicate that in the UI
if(_dropTarget != null){
_dropTarget.classes.add('over');
}
}

 

onTouchEnd

The implementation of the onTouchEnd method will be identical to the onDrop method in the last tutorial I wrote – Getting Started : Dart. You are completing the same logic think of lifting your finger off the screen as depressing the mouse button. If you are unsure of the implementation you can look back at the last post here

 

Conclusion 

I still have some work to do in regards to the css styling as we dont have as many transition states with touch events I have to streamline the css to provide a smoother dragging effect. However this should get most people started with implementing their own Drag n Drop HTML5 web app. If you have any questions do post them I will try my best to answer. Im likely to be very busy im working on a new utility library to make creating cross platform interactions much easier, so will post progress on that or anyone interested in helping out can contact me here too.

[Update PicsAPuzzle responsive template is broken at time of writing so please be patient with it]

Thank for reading, Dont forget to check out PicsAPuzzle on Github I aim to create a few more small apps to experiment with different interactions. All constructive feedback is welcome.

Chris

Getting Started : Dart

Recently  I have been experimenting with Google Dart and HTML. After doing some web development with HTML5/JS I found the javascript files very quickly became huge and complicated pieces of javascript. I tried Dart in the hope that it could solve all my javascript woes and make development a little more familiar to Java. The following is a quick tutorial on how to create a small app with Dart.

View App

Getting Started

You can download the IDE and SDK from  – http://www.dartlang.org/

On the dartlang website you may want to look at some of the code samples one of which I used to construct this small application.

Opening the Dart IDE you should see its very similar to Eclipse.

  • Create a new Application File -> New Application or First Icon in Toolbar
  • Name the application
  • Select Generate content for basic web app content

Dart Editor will generate 3 files of interest <app_name>.css/html/dart

Pressing the Run Button (Play Icon) – you should see this

Dart generated sample code

Do as the App says and experience a nice transformation

Creating my First Application

I decided I wanted to create something fun and that could be incredibly simple and that I could gradually make more complex. I came up with a Picture Puzzle with the base goal of creating a small image split into tiles that can be re ordered to recreate the image.
I started with the Drag n Drop code sample supplied on the Dartlang code samples. Lets start with the HTML for the basic version of the app. I wanted a 3*3 grid of tiles for ane asy to complete grid. As an initial design we will hard code the tiles later as we get more comfortable we can dynamically add these.


<div id="container" class="board">

<div id=”tiles”>
<div id=”tile1″ draggable=”true”></div>
<div id=”tile2″ draggable=”true”></div>
<div id=”tile3″ draggable=”true”></div>
<div id=”tile4″ draggable=”true”></div>
<div id=”tile5″ draggable=”true”></div>
<div id=”tile6″ draggable=”true”></div>
<div id=”tile7″ draggable=”true”></div>
<div id=”tile8″ draggable=”true”></div>
<div id=”tile9″ draggable=”true”></div>
</div>

</div>

Hopefully this is self explanatory, each div tag will represent a tile and each tile has to have the draggable attribute set to true so that we can move them. Easy !!

The Dart code now, this is the new exciting stuff. You have your tiles parent element that contains all the pieces of the puzzle. View the full dart code here I will only explain main snippets below to save this being an enormous post!

Adding Drag n Drop functionality

There are a few Element event handlers that have to be set to make our tiles drag n drop nicely.

  1. on.dragStart
  2. on.dragEnd
  3. on.dragEnter
  4. on.dragOver
  5. on.dragLeave
  6. on.drop

It is possible to code drag n drop much simpler with basic start/end/drop functions but this way we can make it perform much smoother. The code here is very similar to the drag n drop HTML5 sample so take a look at that for a good base implementation.

onDragStart Event


void _onDragStart(MouseEvent event) {
//Get the tile being dragged by user from the MouseEvent
Element dragTarget = event.target;
//add css to show the tile is in motion
dragTarget.classes.add('moving');
_dragSourceEl = dragTarget;
event.dataTransfer.effectAllowed = 'move';
//let the browser know which element is moving
event.dataTransfer.setData('text/html', dragTarget.innerHTML);
}

The above method initiates the dragging telling the browser we are moving dragTarget and assigns a custom css to show the user that the item is in motion.

onDrop Event

void _onDrop(MouseEvent event) {
// Stop the browser from redirecting.
event.stopPropagation();
// Don't do anything if dropping onto the same column we're dragging.
Element dropTarget = event.target;
if (_dragSourceEl != dropTarget) {
// get the image of tile we are dragging.
var bg_image_old = dropTarget.style.backgroundImage;
//Swap the images
dropTarget.style.backgroundImage = _dragSourceEl.style.backgroundImage;
_dragSourceEl.style.backgroundImage = bg_image_old;

To see more of the methods and CSS behind the drag n drop please check out github
This simple example covers the main aspects of dragging and dropping elements using DART and shows some of the syntax you can expect to use in DART. The next problem was assigning images to each DIV in a random order.

Dart has a Maths package you can import straight into your project, those familiar with java will definitely recognize these functions. To use the Math package add the following to the top of your .dart file.

#import('dart:math');

I stored all my tiles using key value pairs in a Map


tiles = new Map();
tiles[1] = "url(img/pgriffin_tiles_01.png)";

This will allow me to quickly access each image and map the images to individual tiles.Next I needed a way to assign a pictures to tiles randomly, this is done effortlessly with using a random number generator, See code below:


var rand = new Random();
var num = rand.nextInt(10);
var imgUrl = tiles[num];

This generates my numbers 0-9 and I keep track of what has been generated to assign all the images in the map to a tile div.

Those familiar with object orientated languages java,C# will recognize this syntax and function. Which is what I think makes Dart such an appealing language everything is familiar,easy and accessible.

this covers the most interesting parts of the code in this very simple demo app designed to help beginners get to grips with Dart. I will post link to main application running soon. Here is a picture for now

After stage 1 approx 1 – 2 hours work. With a few Bootstrap/Css bells and whistles

Conclusion
So far I am really enjoying developing with DART, It really does take some of the pain out of javascript and has a good IDE and plenty of samples and tools to help you get started. I will continue to post progress of my application as I grow more comfortable with the language. Hope this has been helpful or atleast a good preview of what DART offers.