Newer posts are loading.
You are at the newest post.
Click here to check if anything new just came in.

February 24 2014

15:05

February 20 2014

16:44

January 30 2014

14:00

JavaScript Animation That Works (Part 2 of 4)

In the last post, we introduced the idea of spriting, an easy way to animate in JavaScript that works in all browsers. We also walked through how to set up the sprite as a background image for a div and then use a line of JavaScript to change the background position to make it appear as if the image has moved.

In this post, we will use this technique to animate both running and jumping motions. In order to create the animation, we will need to quickly change the background position at a regular interval. Take a look again at the sprite we are using.

javascript-spriting-j

Meet J, the mascot for my company, Joust Multimedia.

In our example, we have ten total images: one of J standing facing right, three of J running to the right and one of J jumping while facing right (with the same number of each frame facing left). Let’s start with making him run to the right. In order to make our image look like it is running, we will need to do two things: change the sprite to a different image and move the div towards the right.


Running to the Right Animation

We certainly won’t want to be stuck clicking different buttons to cycle through the sprites, so we will need to create some functions that do this automatically.

For our running function, we want to:

  1. Move the div towards the right slightly
  2. Move to the next frame of animation
  3. Pause for a fraction of a second (to preserve the “persistence of vision” illusion)
  4. Loop the function again

Fortunately, there is an easy way to loop with functions. A native command in JavaScript called setTimeout will allow us to create a timed delay, after which we will call the function again (from inside the function).

function run_right(){
  // Move slightly to the right ...
  // Change to the next frame of animation ...

  // this will call 'run_right' again after 200 milliseconds
  setTimeout(function(){run_right();}, 200); 
}

So now we have a function that will call itself again five times a second (which will be fast enough to create animation for our purposes). Remember here that browsers are not terribly accurate with their timers. You can specify timing to the millisecond, but that doesn’t mean your script will run at that timing exactly!

Our next problem to tackle is how is our function going to know which sprite to change to? In our example, we will need to cycle back and forth through our three images (to have four total frames of animation). To do this, we are going to pass our function a bit of information to tell it which slide to switch to. Once in the function, we will do a test that will check which slide we should be on, then switch the background position to the correct sprite. When we call the function again, we will pass the next slide as the argument.

function run_right(slide){
  // Move slightly to the right ...
  switch (slide){ // this switch statement checks for different possibilities for 'slide'
    case 1: // if 'slide' equals '1' ...
      document.getElementById('j').style.backgroundPosition = "-40px 0px";
      setTimeout(function(){run_right(2);}, 200);
      break;
    case 2: // if 'slide' equals '2' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(3);}, 200);
      break;
    case 3: // if 'slide' equals '3' ...
      document.getElementById('j').style.backgroundPosition = "-120px 0px";
      setTimeout(function(){run_right(4);}, 200);
      break;
    case 4: // if 'slide' equals '4' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(1);}, 200);
      break;
  }
}

And now when we call the function for the first time, we will need to make sure we pass the starting slide.

<input type="button" value="Run Right" onclick="run_right(1);" />

Similarly, to move our div to the right slightly, we can pass the initial left attribute of the div, then move the div slightly each time the function is called.

function run_right(slide, left){
  
  left = left + 15; // Increase his left attribute by 15px
  document.getElementById('j').style.left = left+"px";
  
  switch (slide){ // this switch statement checks for different possibilities for 'slide'
    case 1: // if 'slide' equals '1' ...
      document.getElementById('j').style.backgroundPosition = "-40px 0px";
      setTimeout(function(){run_right(2, left);}, 200);
      break;
    case 2: // if 'slide' equals '2' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(3, left);}, 200);
      break;
    case 3: // if 'slide' equals '3' ...
      document.getElementById('j').style.backgroundPosition = "-120px 0px";
      setTimeout(function(){run_right(4, left);}, 200);
      break;
    case 4: // if 'slide' equals '4' ...
      document.getElementById('j').style.backgroundPosition = "-80px 0px";
      setTimeout(function(){run_right(1, left);}, 200);
      break;
  }
}

And when we initially call the function, we need to make sure we pass the current left position of our div.

<input type="button" value="Run Right" onclick="run_right(1, document.getElementById('j').offsetLeft);" />

Stopping the Animation

So, now we have a function that, when called, will animate J to run to the right. Unfortunately, we have no way to stop it. First of all, we will need to make the function stop calling itself if J runs to the edge of our stage. To do that, every time the function runs, we will check an if statement to see if J has room to keep running. If so, we will run the function like normal. If not, we will stop calling the function and return him to the standing sprite.

function run_right(slide, left){
  // If we can add 15 pixels to the left and have J's right edge not be at the stage's right edge ...
  if ((left + 15) < (document.getElementById('stage').offsetWidth - document.getElementById('j').offsetWidth)){
    // We have room! Continue like normal here
  } else { // if we are on the right edge, we need to stop calling the function and return to standing
    document.getElementById('j').style.backgroundPosition = "0px 0px";
  }
}

Finally, we will want to have a way to stop the function, when needed. We can set the setTimeout() command to a variable, then stop it with the clearTimeout() command. In order to do this, we will need to declare that variable outside of the function, so that we will be able to refer to it later. For now, we will declare it as a global variable. This is terrible coding practice, but we will correct this in the next post. This is what our function looks like.

var timer;

function run_right(slide, left){
  if ((left + 15) < (document.getElementById('stage').offsetWidth - document.getElementById('j').offsetWidth)){
    left = left + 15; // Increase his left attribute by 15px
    document.getElementById('j').style.left = left+"px";
  
    switch (slide){ // this switch statement checks for different possibilities for 'slide'
      case 1: // if 'slide' equals '1' ...
        document.getElementById('j').style.backgroundPosition = "-40px 0px";
        setTimeout(function(){run_right(2, left);}, 200);
        break;
      case 2: // if 'slide' equals '2' ...
        document.getElementById('j').style.backgroundPosition = "-80px 0px";
        setTimeout(function(){run_right(3, left);}, 200);
        break;
      case 3: // if 'slide' equals '3' ...
        document.getElementById('j').style.backgroundPosition = "-120px 0px";
        setTimeout(function(){run_right(4, left);}, 200);
        break;
      case 4: // if 'slide' equals '4' ...
        document.getElementById('j').style.backgroundPosition = "-80px 0px";
        setTimeout(function(){run_right(1, left);}, 200);
        break;
    }
  } else {
    document.getElementById('j').style.backgroundPosition = "0px 0px";
  }
}

And we can create another function to stop the running timer and return the sprite to the standing image.

function stop_running(){
  document.getElementById('j').style.backgroundPosition = "0px 0px";
  clearTimeout(timer);
}

Running to the Left Animation

Now by borrowing the code from our run_right function, we can create another function to make a run_left function, with just a few modifications.

function run_left(stage, left){
  if ((left - 15) > 0){
    left = left - 15;
    document.getElementById('j').style.left = left+"px";
    switch (stage){
      case 1:
        document.getElementById('j').style.backgroundPosition = "-40px -50px";
        timer = setTimeout(function(){run_left(2, left);}, 200);
        break;
      case 2:
        document.getElementById('j').style.backgroundPosition = "-80px -50px";
        timer = setTimeout(function(){run_left(3, left);}, 200);
        break;
      case 3:
        document.getElementById('j').style.backgroundPosition = "-120px -50px";
        timer = setTimeout(function(){run_left(4, left);}, 200);
        break;
      case 4:
        document.getElementById('j').style.backgroundPosition = "-80px -50px";
        timer = setTimeout(function(){run_left(1, left);}, 200);
        break;
    }
  } else {
    document.getElementById('j').style.backgroundPosition = "0px -50px";
  }
}

Jumping Animation

Finally, we need to create a jump function. We will pass two arguments to this function, one that will track whether the div is currently moving up or down and another that will track the current top attribute of the div. Between the two, we will determine which direction the div needs to move next, and how far (we will move the div less distance near the arc of the jump to simulate acceleration with gravity).

function jump(up, top){
  /*
   * We change J to his jumping sprite ...
   */
  document.getElementById('j').style.backgroundPosition = "-160px 0px";
  /*
   * Here, we need to decide whether he should be traveling up or down...
   */
  if (up && (document.getElementById('j').offsetTop > 20)){
    // if he is currently moving up, and he is more than 20 pixels from the top of the stage ...
    top = top - (top * .1); // This gives us a slight arc in the jump, rather than a constant movement like running
    document.getElementById('j').style.top = top+"px"; // Change his position
    timer = setTimeout(function(){jump(up, top);}, 60); // Then call the function again
  } else if (up) {
    // if he is currently moving up, but he is almost at the top of the stage and needs to come back down...
    up = false; // we switch the 'up' variable so he will be falling in the next loop
    timer = setTimeout(function(){jump(up, top);}, 60);
  } else if (!up && (document.getElementById('j').offsetTop < 115)){
    // if he is moving down, but is more than 5px from the ground, he will continue to fall...
    top = top + (top * .1); // His fall will slightly accelerate
    document.getElementById('j').style.top = top+"px";
    timer = setTimeout(function(){jump(up, top);}, 60);
  } else {
    // If he is moving down, and he is within 5px of the ground...
    document.getElementById('j').style.top = "120px"; // Place him on the ground
    document.getElementById('j').style.backgroundPosition = "0px 0px"; // return to standing sprite
    // We do not call the loop anymore since he is standing still at this point
  }
}

Now we can put all four of our functions into buttons and have a working prototype of a running and jumping animation! Please check out the source code for this page with comments and download the sprite sheet that I used, if you’d like.


Conclusion

Now, although we have a working prototype here, you may notice it is a little buggy. When you click on more than one button at a time, the script will try to run both at once. Or, if you click the jump button again on the way down, J will continue to fall forever. Also, as I mentioned earlier, we have global variables in our script, which means it might be difficult to add this code into an existing page without crashing other JavaScript (which is also why I didn’t try to run this code within this blog page). In our next post, we will clean up all of these bugs and talk about the concept of encapsulation and why it is important to write good code in the real world.

January 14 2014

18:31

JavaScript Animation That Works (Part 1 of 4)

HTML is the language the web is built in, and it is kind of a strange beast. Although it was originally intended as a way to easily share academic information across the Internet, it has been slowly transformed to accommodate the media-rich environment we know and love, sort of like a cherished lawn mower that has been fitted with jet engines.

Because of the haphazard nature of HTML (and JavaScript, the programming language that manipulates elements in HTML and makes them interactive), sometimes we have to think outside the box a bit. In this tutorial series, I will show you how to do cross-browser animation using a method called spriting, using only JavaScript and HTML (and a bit of CSS too). And, because this is a learning opportunity (and I am stubborn and like to do things the hard way), we will be doing it all without any external libraries (like jQuery).

This will be a four-part series – I will explain the spriting itself in part one (this article) with some basic JavaScript, but then in later installments we will move into some intermediate techniques like encapsulation, event handling, and touch screen support.

So let’s get started!


What Is Animation?

Animation is based on a phenomenon called persistence of vision, which basically says that if your brain sees lots of similar still images fast enough, then it will appear as though it is one moving image. Every kind of film or video uses this basic technique – many, slightly different frames are shown in quick succession to make something appear moving. Film typically runs at 24 frames per second (₁), while broadcast television in North America is shown at 29.97 frames per second (₂). So, in other words, what we want to do is create something that shows similar frames really quickly (several times a second).


The Difficulties on the Web

There are two main reasons animation is difficult to use on the web:

  1. The first is that different web browsers have different ways they interpret HTML and JavaScript, so what works on one device often doesn’t work on another. Flash works great on most browsers, but support is starting to drop for it and iOS devices won’t allow it at all. Canvas has a lot of potential, but Internet Explorer 8 doesn’t support it. Same goes with Adobe Edge Animate. GIFs work on everything, but you can’t control the animation or make it interactive.
  2. And for the second, every time an image is served on a web page, a separate request is made between the browser and server. These requests can add up, even over a lightning fast Internet connection, making having several frames each second unmanageable.

The Solution: Spriting

One way around these problems is to make a sprite sheet. In elements like div‘s, we can set a background image for the div that may be larger than the element itself. We can also set the background position so that we determine exactly which part of the larger image will show. A sprite sheet is a larger image made of several smaller images that we can move around so that it could take the place of many small images. Take a look at the example below, using J, the mascot of my company Joust Multimedia:

javascript-spriting-j

Although there are ten different images of J, they are placed together on one larger PNG file (we are using PNGs because they can show transparency). If we have a div that is only the size of one of the images, and we set this PNG as the background, it will look like a single image.

See the Pen hazdm by Steven Riche (@StevenRiche) on CodePen.

Although this seems like a lot of trouble to go through to show an image, this method nicely fixes the two issues we had before. With very little JavaScript (one line!), you can change the background position of a div, and it works on everything. Also, since all of these frames are on the same image, it will only take one request to load that image in the page. So, once the page loads, it can switch between sprites with no problem at all.

So how do we set this up to animate easily then? The first step is to create the sprite sheet. You will want to know what the final dimensions of your image should be, and space the sprites accordingly in a grid. For instance, my J image is going to be 40px wide by 50px tall, so I lined up my sprites exactly 40px apart horizontally and exactly 50px apart vertically. It will probably be easiest if you set your starting sprite in the upper left corner.

Then we will set up a div with a bit of CSS to make sure that everything appears properly.

<div id="stage">
	<div id="j" class="character"></div>
</div>

And here is our CSS to make sure the sprite is showing correctly:

.character {
	/*
	 * Very important that we set the height and width of 
	 * our characters to the height and width of the sprites
	 */
	height:50px;
	width:40px;
	/*
	 * We need to position them absolutely so we can have full  
	 * control over their position within the stage
	 */
	position:absolute;
	left:100px;
	top:120px;
}

#j {
	/*
	 * And now we set the background image for the character div 
	 * to be the first sprite (in the upper left corner)
	 */
	background-image: url('j.png');
	background-repeat:no-repeat;
	background-position:0 0;
}

Notice the following things:

  • We specify the width and height of the div to the size of our sprite
  • We specify the background-repeat to 'no-repeat'
  • We specify the background-position to '0 0' – this will show the sprite in the top left corner

Now, it will just take a single line of JavaScript to change the background position to show the next sprite.

document.getElementById('j').style.backgroundPosition = '-40px 0px';

Here, we are selecting the element (with id='j'), and setting the style attribute 'backgroundPosition'. Notice that it is spelled 'backgroundPosition' in JavaScript, and not like 'background-position' in CSS. Also notice that in JavaScript, the 'px' is required for both the x and y amount – we cannot just pass it numbers. And because we are moving the background image, we have to move it in the opposite direction from what you might expect – to move to the sprite on the right, we have to have the image move 40px to the left.

Now, if we just have something simple to execute this code (like a button), we can see the frames changing in action.

See the Pen DIsgk by Steven Riche. Check out the source code for this page. It has all of the examples here with thorough comments. And here is a link to the sprite sheet I am using.

Next Up

This is still not really animation though – in part two of this series we will actually animate some running and jumping, by creating loops with the different sprites.

By part four, we will be creating mouseovers for a bit of robot action.

See the Pen ByGtv by Steven Riche.


In Conclusion & Drawbacks

Although this can be a great method for animating on the web, there are a few drawbacks. First, it can require you to create each individual frame of animation, which can be time-consuming. Second, browsers don’t have the most accurate of timers for animation, so if it is critical for your animation to be timed perfectly, then this may not work. Finally, mobile Safari (used on iPhones and iPads) has a “feature” where if you have a background image that is either larger than 2MB or larger than 1024 X 1024 X 3 pixels (or 3,145,728 total pixels), it will automatically rescale the image, ruining the spriting effect. This means that really large sprites, or animations with a very large number of sprites, is out of the question. But, for simple, small animations that you want to be very interactive, this is an easy and great way to get something that works everywhere.

Interesting Side Notes

1: Before sound was introduced with film, there wasn’t really a standard frame rate. The cameras were operated by a hand crank, so if you had a rookie cameraman the frame rate might slow down and speed up dramatically unintentionally. Similarly, less reputable theaters were notorious for telling their projectionists to crank the projector quicker to speed up the show so they could fit in more screenings. This is also why we stereotypically think of pre-sound movies as moving around comically fast – most were filmed around 16-18 fps, so when we play them today at 24 frames per second, they are moving faster than they were originally intended.

2: Television was originally broadcast at 30 fps in North America, but color television caused a glitch when shown at that speed. Engineers figured out that they could fix it by slowing down the frame rate by 0.1%, which is why it is now set at 29.97 fps. Also, besides all of the wacky technical issues involved with converting a film in 24 fps to display on television at 29.97 fps, showing television at a faster fps has had an interesting effect on the public. Many people watching the test screenings of “The Hobbit” at 48 fps reported that the increased frame rate made the film look “cheaper”, even though it was much higher quality than a typical film, just because they had grown to associate faster frame rates with watching something on television.

November 04 2013

15:28

Building a Single-Page Dynamic Website using AnimateScroll.js

Advertise here with BSA


Sliding parallax websites incorporate animation with page sections to build a very unique experience. Over the past few years I have found a large number of parallax designs wrapped into a single webpage. Notably this parallax interface may be hard-coded from scratch, but there are lots of free open source plugins to do the job quicker.

In this tutorial I want to demonstrate how we can use AnimateScroll to build a sliding single-page website layout. I’ve kept inner page content to a minimum so we can see exactly how the CSS structure works with the animations. Keep in mind this definitely isn’t a tough concept to implement. But you should have an understanding of page hierarchy and CSS positioning or it gets confusing fast. Check out my live demo example to see exactly what we are making.

jquery animate scroll library single page tutorial preview screenshot

Live DemoDownload Source Code

Getting Started

The first step is to download a local copy of jQuery and grab a copy of the AnimateScroll.js codes from Github. You will only need to copy over a single file animatescroll.js which should be placed alongside your jQuery script.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Dynamic Scrolling with AnimateScroll.js - DesignM.ag Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designm.ag/favicon.ico">
  <link rel="icon" href="http://designm.ag/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/animatescroll.js"></script>
</head>

The inner page structure is fitted to host a single fixed navigation bar at the top of the page. I have this wrapped inside an HTML5 <nav> using an internal unordered list. Considering the page is meant to display at 100% width I haven’t used any outer wrapper.

  <nav id="topnav" class="clearfix">
    <ul>
      <li><a href="body" id="homenavlink">Home</a></li>
      <li><a href="#about" id="aboutnavlink">About</a></li>
      <li><a href="#portfolio" id="portfolionavlink">Portfolio</a></li>
      <li><a href="#contact" id="contactnavlink">Contact</a></li>
    </ul>
  </nav><!-- @end #topnav -->
  
  <!-- BG http://architecture.desktopnexus.com/wallpaper/1581572/ -->
  <section id="pagetop" class="contentpg">
    <h2>First Section</h2>
      
  </section><!-- @end #pagetop -->
  
  <!-- BG http://nature.desktopnexus.com/wallpaper/1581411/ -->
  <section id="about" class="contentpg">
    <h2>About Someone</h2>
  </section><!-- @end #about -->
  
  <!-- BG http://architecture.desktopnexus.com/wallpaper/1582636/ -->
  <section id="portfolio" class="contentpg">
    <h2>Portfolio Work</h2>
  </section><!-- @end #portfolio -->
  
  <!-- BG http://abstract.desktopnexus.com/wallpaper/1583541/ -->
  <section id="contact" class="contentpg">
   <h2>Contact Some People</h2>
  </section><!-- @end #contact -->

Depending on how you want your content to appear it may be worthwhile to create a wrapper class. This wrapper can be placed inside each content section for centering the text, or keeping it at some fixed width value.

Each of my sections is covered with a fullscreen background image. Since there is very little content they are only maxed out to a certain height. But with natural CSS3 background images we can expect the design to scale for any monitor resolution. Let’s delve into the stylesheet and really see how this all comes together.

Page Designs

Inside my styles.css file is everything necessary for the layout to render properly along with the AnimateScroll.js plugin. First you’ll notice one small import statement to include a Google web font used for custom heading text. This is followed by a long list of CSS resets to update the default page document structure.

It gets interesting once we break into the core page design. #topnav is fixed to the top of the page at a height of 55px. The links behave as parallax sliders moving around to sections within the webpage itself. You can build this navigation anywhere in your layout – but keeping it at the top makes more sense in a fixed position.

/** page structure **/
#topnav {
  display: block;
  position: fixed;
  top: 0;
  height: 55px;
  width: 100%;
  background: #779ec0;
  border-bottom: 2px solid #628aad;
}
#topnav ul  { padding-left: 80px; }

#topnav ul li { 
  display: block;
  width: auto;
}

#topnav ul li a {
  display: block;
  float: left;
  line-height: 55px;
  margin-right: 10px;
  padding: 0 15px;
  font-weight: bold;
  font-size: 1.2em;
  color: #fff;
  text-decoration: none;
}
#topnav ul li a:hover {
  background: #62819d;
}

Each of the internal section elements has their own ID to designate unique background images. But they also use the class .contentpg for strict duplicated rules. Notably I’ve written some internal padding along with a maximum height of 550 pixels. Each content section may be longer or shorter depending on how much you need to write. Feel free to edit this value so that it works best on your project(s).

/** page sections **/
.contentpg {
  display: block;
  min-height: 550px;
  padding: 55px 80px;
}

#pagetop {
  background-image: url('../img/bg1.jpg');
  background-repeat: no-repeat;  
  background-size: cover; 
  /*css hack for ie*/     
  filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg1.jpg',sizingMethod='scale');
  -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg1.jpg',sizingMethod='scale')";
}

#about {
  background-image: url('../img/bg2.jpg');
  background-repeat: no-repeat;  
  background-size: cover; 
  /*css hack for ie*/     
  filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg2.jpg',sizingMethod='scale');
  -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg2.jpg',sizingMethod='scale')";
}

#portfolio {
  background-image: url('../img/bg3.jpg');
  background-repeat: no-repeat;  
  background-size: cover; 
  /*css hack for ie*/     
  filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg3.jpg',sizingMethod='scale');
  -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg3.jpg',sizingMethod='scale')";
}

#contact {
  background-image: url('../img/bg4.jpg');
  background-repeat: no-repeat;  
  background-size: cover; 
  /*css hack for ie*/     
  filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg4.jpg',sizingMethod='scale');
  -ms-filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../img/bg4.jpg',sizingMethod='scale')";
}

The codes handling fitted background images are from the popular CSS-Tricks article covering perfect CSS-based fullscreen backgrounds. CSS3 is not supported in many older browsers and so this trick is great for modern websites. But if you are concerned about legacy support I would highly recommend using another jQuery plugin such as Backstretch.

Initialize AnimateScroll.js

With the page structure in place and the CSS designed nicely it is time to apply the animation. There are 3 options you can go over in the documentation but it’s all very straightforward. The easing option controls the animation style, padding gives extra space from the top of an element, and scrollSpeed adjusts how fast or slow the animation happens.

$(function(){
  $('#topnav ul li a').on('click', function(e){
    e.preventDefault();
    var scrolldiv = $(this).attr('href');
    
    $(scrolldiv).animatescroll({padding:50});
  });
});

This small block of code should be placed inside a script tag just before closing the document body. If you wish to write other scripts then it could be instead written into an external JS file. The selector is targeting any link within the top navigation section.

Once the user clicks on a link we can stop the href value from loading into the address bar with event.preventDefault(). However we do need this href value because it will designate which content section we are scrolling into. I saved this into a new variable scrolldiv which is then turned into a selector for the .animatescroll() method.

Notice the single option I am using is just related to padding. Since the top navbar is always fixed on the screen we need to relieve some extra room. This option works for all the lower content areas, but the very top home section needs additional CSS padding from the body. Now the navigation bar will never get in the way of any content on the page.

jquery animate scroll library single page tutorial preview screenshot

Live DemoDownload Source Code

Closing

I know this is a fairly basic demonstration but I made it this way to behave almost like a template. Anyone who is willing to build their own single-page website layout could use this tutorial as a starting point. There are also many alternative parallax plugins which you could try looking into. If you want to see how my example works feel free to download a copy of the project source code and play around to see what you can build.


Advertise here with BSA

September 25 2013

13:46

Building Vertical-Tabbed Content Sections with jQuery

Advertise here with BSA


Ajax-style loading boxes are useful when displaying large sets of related data. Think about something like an FAQ page, knowledgebase, or support system. Any type of navigation is often suitable as long as the user can determine how to navigate between content areas.

In this tutorial I want to demonstrate how we can build a custom vertical content section using jQuery. All of the internal content is held inside div containers which can be navigated with an icon-based menu. This content isn’t loaded externally via Ajax, but is instead hidden & displayed using content sections already on the page. Check out my live sample demo to get an idea of what we are building.

jquery vertical content tabs sections tutorial preview screenshot

Live DemoDownload Source Code

Getting Started

There are only two required files we need for this dynamic content section to work. The first is jQuery which you can download in a compressed local format. The other is Font Awesome which is a free open source CSS3 icon webfont. This means we can include certain fonts using @import and render icon graphics as font elements in the page.

<!doctype html>
<html lang="en-US">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>jQuery Vertical Tabbed Content Sections</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="http://designm.ag/favicon.ico">
  <link rel="icon" href="http://designm.ag/favicon.ico">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <link rel="stylesheet" type="text/css" media="all" href="css/font-awesome.min.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
</head>

This is what my document header looks like. I have included these two required items along with my core styles.css stylesheet. Also be sure that when you include the Font Awesome CSS file that you also copy over the entire /font/ directory. This includes all the important file types such as TTF and OTF, which are necessary to recognize any of the icon characters.

Creating Inner Body Content

The two main sections of the page are held within a single inner wrapping div. Obviously the navigation is much smaller than the content, so I have the navbar floating left without a connecting background. #sidemenu is actually an unordered list of items which display as block elements inside a fixed-width container.

<ul id="sidemenu">
  <li>
    <a href="#home-content" class="open"><i class="icon-home icon-large"></i><strong>Home</strong></a>
  </li>

  <li>
    <a href="#about-content"><i class="icon-info-sign icon-large"></i><strong>About</strong></a>
  </li>
  
  <li>
    <a href="#ideas-content"><i class="icon-lightbulb icon-large"></i><strong>Ideas</strong></a>
  </li>
  
  <li>
    <a href="#contact-content"><i class="icon-envelope icon-large"></i><strong>Contact</strong></a>
  </li>
</ul>

Now the other page element uses the ID #content which links to a number of internal div elements. These are labeled according to the navigation anchor links with the various IDs of home, about, ideas, and contact.

<div id="content">
    <div id="home-content" class="contentblock">
      <h1>The Main Page!</h1>
      <p>I swear this has some really great stuff. Content is courtesy of <a href="http://bluthipsum.com/">Bluth Ipsum</a>.</p>
      
      <p>Smack of ham. What is she doing at a beauty pageant? Is she running the lights or something? She's always got to wedge herself in the middle of us so that she can control everything. Yeah. Mom's awesome.</p>
      
      <p>Probably out there without a flipper, swimming around in a circle, freaking out his whole family.</p>
      
      <p>Fun and failure both start out the same way.</p>
    </div><!-- @end #home-content -->
    
    
    <div id="about-content" class="contentblock hidden">
      ...
    </div><!-- @end #about-content -->
    
    <div id="ideas-content" class="contentblock hidden">
      ...
    </div><!-- @end #ideas-content -->
    
    <div id="contact-content" class="contentblock hidden">
      ...
    </div><!-- @end #contact-content -->
</div><!-- @end #content -->

Notice that each of the inner div elements uses .contentblock as an additional class for styling. Yet #home-content is the only one without the extra .hidden class because this homepage content should immediately display once everything finishes loading. We can use jQuery to un-hide the other page areas and re-hide the homepage content section when switching in the navigation.

CSS Design Styles

With the Font Awesome CSS already included we can use this font family anytime. I’ve also linked to another font family named Cantora One which is hosted by Google Web Fonts. Other than this my stylesheet uses a few basic resets along with a core container for each inner div section.

@import url('http://fonts.googleapis.com/css?family=Cantora+One');

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  outline: none;
  -webkit-font-smoothing: antialiased;
  -webkit-text-size-adjust: 100%;
  -ms-text-size-adjust: 100%;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
html { overflow-y: scroll; }
body { 
  font-size: 62.5%; 
  line-height: 1;
  padding: 45px 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background: #fff url('../images/bg.png'); /* http://subtlepatterns.com/connected/ */
}

br { display: block; line-height: 1.6em; } 
img { border: 0; max-width: 100%; }

h1 {
  font-family: 'Cantora One', Arial, sans-serif;
  font-size: 3.0em;
  line-height: 1.6em;
  margin-bottom: 10px;
  color: #787878;
}

p {
  font-size: 1.4em;
  line-height: 1.25em;
  color: #575757;
  font-weight: normal;
  margin-bottom: 10px;
}

a { color: #8dadd8; }
a:hover { color: #7299cf; }

/* main page */
#w {
  display: block;
  width: 900px;
  margin: 0 auto;
  background: none;
}


#content {
  display: block;
  background: #fff;
  padding: 0px 15px;
  margin-left: 80px;
  -webkit-box-shadow: 1px 2px 1px rgba(0,0,0,0.4);
  -moz-box-shadow: 1px 2px 1px rgba(0,0,0,0.4);
  box-shadow: 1px 2px 1px rgba(0,0,0,0.4);
  min-height: 300px;
}


.contentblock {
  display: block;
  padding: 15px 20px;
}

.contentblock.hidden {
  display: none;
}

You will notice that I’ve only included a white background on the main #content div which keeps the navigation off to the side as a separate element. There are so many different ways you could design this interface, but I like seeing the background on the active link turn white and appear to blend into the page itself. Also I have .contentblock.hidden set to no display which we can manipulate directly in jQuery.

/* side navigation */
#sidemenu {
  margin: 0;
  padding: 0;
  width: 80px;
  float: left;
  background: #e8e8e8;
  border-right: 1px solid #c9c9c9;
}


#sidemenu li { display: block; text-align: center; border-top: 1px solid #fff; font-size: 1.1em; }

#sidemenu li a { 
  display: block;
  padding: 6px 2px;
  color: #555;
  text-decoration: none;
  border-bottom: 1px solid #d1d1d1;

}
#sidemenu li a:hover {
  background: #f2f2f2;
}

#sidemenu li a strong { 
  display: block;
  margin-top: 5px;
}

#sidemenu li a.open {
  width: 101%;
  background: #fff;
}

The outer navigation container is fixed to a width of 80px and floated off to the left side. We can use margins and padding on the other content box to keep these two from overlapping. The #sidemenu element uses a border on the right to encapsulate all the links.

Any anchor link with the additional .open class will be set to 101% width. This means it will be wider than the border and appear to be naturally connected into the page content. Everything else about the nav CSS is related to styling the icons and the text which are held in two separate HTML elements.

jQuery Animations

Finally we get to the bottom of the index.html file which includes a small block of jQuery. The main event handler is triggered whenever a user clicks on the navigation link items. First we want to disable the click event using e.preventDefault(). Since the content is loading dynamically, we don’t want to append the page ID onto the URL unless JavaScript were disabled.

$(function(){
  $('#sidemenu a').on('click', function(e){
    e.preventDefault();

    if($(this).hasClass('open')) {
      // do nothing because the link is already open
    } else {
      var oldcontent = $('#sidemenu a.open').attr('href');
      var newcontent = $(this).attr('href');
      
      $(oldcontent).fadeOut('fast', function(){
        $(newcontent).fadeIn().removeClass('hidden');
        $(oldcontent).addClass('hidden');
      });
      
     
      $('#sidemenu a').removeClass('open');
      $(this).addClass('open');
    }
  });
});

Jumping into the actual logic, we first check if the currently clicked item has a class of .open. If so then the link is already visible so we do nothing. Otherwise we create two new variables named oldcontent and newcontent. Using jQuery .fadeOut() on the old content we can then use a callback function to add the .hidden class while simultaneously showing the new content with .fadeIn().

The final two lines of code adjust the menu item once all the inner content has finished animating. We remove all .open classes from the menu links and then apply it onto the newly selected link item. This all happens within 1-2 seconds of time so it appears very sequential. We could always use a jQuery delay if there was some need to halt the animations. But this generic interface is quite easy to setup and shouldn’t require a whole lot of convoluted scripting.

Final Thoughts

I hope this tutorial may be useful to some web designers or developers who need a similar widget. The codes are easy to transfer into your own script or even into a plugin if needed. Of course, plugin functionality might be more convoluted than we need – but this type of dynamic webpage effect is perfect for section-based content with divisions in the material. Feel free to download a copy of my source codes and see if you can implement this design in your own future projects.


Advertise here with BSA

August 12 2013

13:55

40 CSS3 Animated Button Tutorials And Experiments

In this post, we have compiled a useful set of CSS3 animated button tutorials and different experiment that may fascinate you. As we all know that CSS3 is the most important and crucial aspect of the web designing that can make your website even more appealing and interactive for your visitors.

Since the world of internet is changing and people tend to like those sites that have more interactive elements, many designers now focus on their CSS3 skills. This is because CSS3 skills can help them to a great extent in achieving the desired attractiveness. Here we have presented animated CSS3 button tutorials and experiments for you so that you can learn these techniques. Enjoy checking out this compilation and have more fun in using them for your works.

CSS3 Tricks: Animated Buttons

( Demo | Download )

BonBon (Candy) Buttons

( Demo | Download )

Making a CSS3 Animated Menu

( Demo | Download )

Create a Slick CSS3 Button with box-shadow and rgba

( Demo | Download )

CSS3 Colored Buttons

( Demo | Download )

CSS3 Button Snippet

( Demo | Download )

Cufonized Fly-Out Menu jQuery and CSS3

( Demo | Download )

Animated Content Tabs with CSS3

( Demo | Download )

Beautiful Photoshop-like Buttons with CSS3

( Demo | Download )

CSS3 Animated Vignette Buttons

( Demo | Download )

CSS3 Buttons With a Glass Edge

( Demo | Download )

Animated Buttons with CSS3

( Demo | Download )

CSS3 Animated Bubble Buttons

( Demo | Download )

Creating CSS3 animated menu

( Demo | Download )

Creating Fantastic Animated Buttons using CSS3

( Demo | Download )

CSS3 multilevel menu with transition and animation

( Demo | Download )

Impressive CSS3 animated button

( Demo | Download )

Radioactive Buttons

( Demo | Download )

Experimental Shadow

( Demo | Download )

More CSS3 Fun

( Demo | Download )

Build Kick-Ass Practical CSS3 Buttons

( Demo | Download )

Halftone Navigation Menu With jQuery & CSS3

( Demo | Download )

Clear Style CSS3 Buttons

( Demo | Download )

Cross Browser Pure CSS3 Button Demo

( Demo | Download )

CSS Only Button – Redux

( Demo | Download )

Learning How to Use CSS pseudo-elements: :before & :after

( Demo | Download )

CSS Buttons with Pseudo-elements

( Demo | Download )

Fading Button Background Images With CSS3 Transitions

( Demo | Download )

CSS3 – Animated Button With CSS Transition

( Demo | Download )

CSS3 Buttons

( Demo | Download )

Zardi Pack of CSS3 Buttons

( Demo | Download )

Download Me!

( Demo | Download )

UI Kit Buttons

( Demo | Download )

Animated Sliding Menu With CSS3

( Demo | Download )

CSS3 Minimalistic Navigation Menu

( Demo | Download )

jQuery style menu with CSS3

( Demo | Download )

Sweet tabbed navigation using CSS3

( Demo | Download )

Just some other awesome CSS3 buttons

( Demo | Download )

A Bunch of Soft, Customizable Pressure Buttons in CSS

( Demo | Download )

Shiny Knob Control with jQuery and CSS3

( Demo | Download )

April 25 2013

07:30

Surviving the Zombie Apocalypse with HTML5 and SVG #2: Text, Paths and Basic Animation


  
zombie-apocalypse-2

The first article in this series covered the basics of SVG, an overlooked, underappreciated aspect of HTML5. While different browsers implement SVG in different ways, the previous walkthrough described how to create text, incorporate SVG images and build basic shapes such as circles, polygons and paths in a way that all browsers recognize.

April 09 2012

07:00

September 28 2011

16:13

How to Animate Threaded Comments with CSS and jQuery

With many social applications the use of threaded comments has become a staple in functionality. Webmasters today are focusing much more on user experience rather than content generation, and because of this there has been a rise in custom animation effects.

Below I’ll be going over a guide to building your own custom jQuery threaded comments from scratch. For the ease of our tutorial we won’t be using any backend system to actually store the data anywhere. This means no MySQL databases or PHP calls to a server – all comments are added in-page and will be lost upon page refresh.

jQuery Animated Comments Thread

Live DemoDownload Source Code

Granted, the system is very simple to work with and extrapolate data from. This tutorial not only introduces the inner workings of jQuery, but gives developers a framework of which to base a simple comments application on.

As always if you have questions feel free to post them in the comments below. Much of the code introduced here is easy to understand and well documented in the jQuery wiki.

Starting with Core HTML

To get started we should focus on document structure and HTML processing. Jumping into the beginning I’ve created a directory named jquery-comments which will include all of our project files. There isn’t much required to include here.

The list starts with an index.html and style.css document overview. These two docs will contain your page structure and layout, respectively. We’ll also need a .js file to house our custom jQuery functionality. I’ve named this file “jcs.js”, short for jQuery comments. But feel free to name the script anything you desire.

Full Preview for Application

The last step I’ve done is to create an images directory. Inside I have a few pre-cropped avatars for our example, along with a comment bubble icon for additional page effects. To get started let’s example the proper code inside index.html first!

    <title>CSS/jQuery Animated Threaded Comments</title>

We have a heading area just like any other webpage instilled at the top of our document. Inside we’ve included our style.css and also our remote JavaScript file. Additionally I’ve added the jQuery 1.4.2 miniaturized library hosted in Google’s code repositories. This has the benefit of reducing calls to the server at runtime and keeping your physical file count low.

Comment Blocks

Inside our body we have a division with an ID “comments”. Inside this is where all our code resides. To dive right in let’s examine a piece of code containing the first 3 page comments. The 1st in our set is the root node while the other two are threaded replies.

 <!-- first thread -->
<div class="comment-thread">
    <div class="comment-block">
        <a href="#" class="author-avatar"><img src="http://designm.ag/wp-content/uploads/2011/09/avatar1.png" alt="userman" /></a>
        <p class="comment-top-meta"><strong>userman</strong> <span>posted 7 hr 32 min ago</span></p>
       
        <div class="comment-content">
            <p class="the-comment-post">Here is some sample text for a comment. Man what a nice day outside!</p>
           
            <p class="comment-reply-options"><a class="option-reply">Reply</a></p>
            <div class="showhidecommform"> </div>
        </div>
    </div>
   
    <div class="thread-replies">
        <div class="comment-thread">
            <div class="comment-block">
                <a href="#" class="author-avatar"><img src="http://designm.ag/wp-content/uploads/2011/09/avatar2.png" alt="DuckDude" /></a>
                <p class="comment-top-meta"><strong>DuckDude</strong> <span>posted 5 hr 11 min ago</span></p>
               
                <div class="comment-content">
                    <p class="the-comment-post">Here is a unique rebuttal. Hmm...</p>
                   
                    <p class="comment-reply-options"><a class="option-reply">Reply</a></p>
                    <div class="showhidecommform"> </div>
                </div>
            </div>
            <div class="thread-replies"></div>
        </div>
       
        <div class="comment-thread">
            <div class="comment-block">
                <a href="#" class="author-avatar"><img src="http://designm.ag/wp-content/uploads/2011/09/avatar3.png" alt="snowhockey1" /></a>
                <p class="comment-top-meta"><strong>snowhockey1</strong> <span>posted 4 hr 16 min ago</span></p>
               
                <div class="comment-content">
                    <p class="the-comment-post">Also, by the way if you were wondering. This isn't a real username it's actually pretty fake.<p>
                   
                    <p class="comment-reply-options"><a class="option-reply">Reply</a></p>
                    <div class="showhidecommform"> </div>
                </div>
            </div>
            <div class="thread-replies"></div>
        </div>
   
    </div>
</div>
<!-- @end first thread -->

The code may seem a bit messy at first, but each section does have an echo effect. Each comment in-page is housed inside a div with the class “comment-thread”. The container divisions for “comment-block” houses all of the comment information.

This includes the username and avatar, date/time of posting, comment content, and reply button. Directly after this area we have a new opening division classed under “thread-replies”. Note this is still inside our root node “comment-thread” and will contain further threaded replies to our original.

Linux Reboot Kernels

If you examine the threaded replies closely you’ll notice not only are they also enclosed inside a “comment-thread” but each has their own “thread-replies” section. For internal comments this div is left blank on purpose – this is how we can use jQuery to manipulate and add further comments without refreshing the page.

You may also notice each comment-block contains a unique ID parameter. This would be set by an internal system giving each new comment an incrementing ID value. I’ve generated static values and added them directly into the HTML code per this example, although it’s fully customizable from any alternative CMS.

Accessing the DOM with jQuery

The Document Object Model is a structural way of viewing each web page. It’s built upon HTML nodes which are referenced with each page element and housed within contain child element(s).

With jQuery we are able to access individual elements in our page and manipulate their information. Not only this, but we are also able to add new page elements without even so much as a refresh! Getting started with jQuery code, added below is the first few lines in our script.

$(document).ready(function() {
    var totalcommid = 31;
   
    $(".option-reply").live("click", function() {

We start off with a standard document.ready() clause checking if our page has fully loaded. Once the DOM is ready we can start calling functions and pulling data. We have a single variable set named totalcommid. This is a static number put in place so we don’t accidentally overwrite any existing comment IDs.

The next line is a selector targeting all elements under the classname “option-reply”. These happen to be the small “Reply” hyperlinks placed after each comment. Our code is checking for a click event handler to call an internal function.

In layman’s terms this means jQuery puts a trigger on each “reply” link in our page. Every time one of them is clicked we have an internal function called to display a new comment text field. Once added we either have the option of closing the comment box or adding new content and appending our comment into the thread.

var currtxt = $(this).text();
var curroptlink = $(this);
var cid = $(this).parent().parent().parent().attr("id");
var poundcid = "#link-"+cid;
       
var htmlform = '&lt;form id="commsubform"&gt;&lt;label&gt;Add Comment:&lt;/label&gt; &lt;textarea id="thecomment" class="commtxtfield"&gt;&lt;/textarea&gt; &lt;br /&gt;&lt;br /&gt; &lt;a class="savecommbtn" id="link-'+cid+'"&gt;Save Comment&lt;/a&gt;&lt;/form&gt;';

The first thing we set are common page variables which we’ll be accessing repeatedly. currtxt is set to the current selector’s text value. curroptlink is a selector targeting the current link we’ve just clicked. Although the code seems mildly repetitive it can save time when manipulating data later in our function.

jQuery programming on laptop studio

cid is a unique variable which contains our current comment thread ID. This takes a bit of DOM traversing until we get to the proper parent element containing our ID value. This is one great aspect to working with jQuery since each comment we add will have the same format, thus our code is fully functional and expands regardless of how many threads.

Our htmlform variable should be pretty self-explanatory. It contains all the HTML code needed to embed into the page for a new comment form. Note we make good use of our cid variable by giving our save link the value of our next comment ID.

Functional Page Manipulation

From here we’ve got most of the variables we need set and ready. We’re already inside of our selector and just need to offer a few more bits of code to exercise.

Getting started we have to understand when our users want to show or hide the comment form. It should be just as easy to close a reply box as to open it. We can accomplish this task with two individual toggle functions based on the current link text.

// toggle between show/hide comment form views
if(currtxt == "Reply") {
    $(this).parent().next(".showhidecommform").html(htmlform);
    $(this).text("Hide form");
}

if(currtxt != "Reply") {
    curroptlink.parent().next(".showhidecommform").html("&nbsp;");
    curroptlink.text("Reply");
}

The logic here is very simple but works well for what we need. Broken apart we see 2 if conditional statements checking the value of our current link text. If the link text says “Reply” we add a new comment form and change the link text to “Hide Form”. If the opposite is true then we just reverse our actions.

The power over documents we control here is only accessible from the many variables we declared earlier in the script. We could change a few more things about the page when a reply link is clicked, although I’ll leave that for you to customize.

The last and final piece of code will translate our comment into an HTML block and append it into the page. Our first jQuery selector looks for an element tagged to the variable poundcid.

// begin translating our comment
$(poundcid).live("click", function() {
    var newcomtxt = $('textarea#thecomment').val();
    var targetcontainer = "#"+cid;
   
    var newcommhtml = '<div class="comment-thread"> <div class="comment-block"> <a href="#" class="author-avatar"><img src="images/avatar2.png" alt="anonymous" /></a> <p class="comment-top-meta"> <strong>anonymous</strong> <span>posted 1 sec ago</span></p> <div class="comment-content"> <p class="the-comment-post">' + newcomtxt + '</p> <p class="comment-reply-options"><a class="option-reply">Reply</a></p> <div class="showhidecommform"> </div> </div> </div> <div class="thread-replies"></div> </div>';
   
    $(targetcontainer).next(".thread-replies").hide().append(newcommhtml).fadeIn();
   
    curroptlink.trigger("click");
});

Digg Homescreen capture

This variable was set earlier in our code and targets the save link we generate with each new comment reply field. For this we add another live() click event handler and call another internal function upon saving.

Adding New Threads Dynamically

The variable newcomtxt is used to pull the current value of our text field and store it. targetcontainer is targeting the root thread based on the ID value. We are adding a hash/pound symbol (“#”) beforehand so we can target the variable inside a jQuery call.

newcommhtml is our largest variable and will be appended over and over into our document. This contains all the commenter’s information – username (in this case anonymous), datetime of posting, and avatar. You may notice there is also built-in code so for each new comment you add there will also be a matching “Reply” feature for further threading.

The second-to-last line is where we target and append our new HTML. We first grab our root element and find the first (and only) iteration of the “thread-replies” div.

First we call the hide() function to hide all internal content. This gives the animated effect of a fade-in when each new comment is added. We then append our HTML code from the variable above along with a fadeIn() function call.

computer registration forms

The trigger() function is called on our curroptlink to force a click event. This points towards our current option link, which at the end of adding a comment should be labeled “Hide Form”. This last line of code makes sure to remove our comment field after successfully adding the comment information into our page.

The last bits of code required will close off our 2 initial jQuery selectors. These include our first click event handler along with the

DOM.ready()

statement. To finish our commands we first increment the comments ID by 1 and return a false Boolean value to stop the page from reloading.

    totalcommid++;
       
        return false;
    });
});

Conclusion

And that’s all we need! The jQuery code may seem a bit intimidating at first glance, especially if you haven’t spent much time in the language. However I can vouch in stating jQuery doesn’t take much time to learn and even newbies to JavaScript will pick up the conventions quickly.

If you have the interest feel free to build around this comment system to include your own server-side functionality. This could include a database system with Ajax calls to permanently store each comment locally with a matching ID.

There are so many things which can be done under the power of jQuery. If you’re interested further try downloading the project demo code and going over a few of the options yourself.


June 15 2011

14:43

35 Of The Best 3D Flash Websites Ever

Beauty will save the world! And digital world will be saved by attractive and magnetic 3D Flash websites which are almost brilliant works of art. This kind of sites quickly draws audience’s attention as it provides rich visual experience. So today we would like to touch the subject of 3D Flash Websites – the most interactive and creative web projects for those who do care about the impression they make.

Developers consider Flash to be a platform with a wide range of opportunities in a website building and presentation, but at the same time it is a rather complex tool which requires certain coding knowledge and skills. Moreover, often Flash sites have essential downsides in comparison with static ones: slow loading and inability of search engines to crawl website pages are mostly called weak points of Flash. But we are sure that Flash is the ultimate solution for creating interactive websites which will blow visitor’s minds. And 3D Flash websites are especially alluring thanks to their fascinating three-dimensional effects. It’s a kind of virtual reality where you are a welcome visitor.

3D Flash websites listed below will make you sit with eyes wide open, even if you are a Flash antagonist. And if you are a true fan of Flash technology then you will definitely be impressed with the interactive beauty displayed on your screen. Just check these 3D Flash websites out!

Biliouris


3d flash websites

Playmedia


3d flash websites

Camp Balcones Springs


3d flash websites

Moment of truth


3d flash websites

Adobe museum


3d flash websites

Galaxy


3d flash websites

Gymnasium


3d flash websites

Grow


3d flash websites

Hop


3d flash websites

Day and Night


3d flash template

eMag 3D


3d flash websites

Liniers


3d flash websites

Paper critters


3d flash websites

Vestas


3d flash websites

Limbus


3d flash websites

PNC


3d flash websites

Optus


3d flash websites

Apoteket


3d flash websites

Whirly


3d flash template

Puma


3d flash websites

Legends of Valhalla


3d flash websites

Immersive garden


3d flash websites

Mechaniks


3d flash websites

Sensisoft


3d flash websites

Danonino’s welt


3d flash websites

The rainbow warrior


3d flash websites

Ben Faragau


3d flash websites

My tunnel


3d flash templates

Whittakers


3d flash websites

100 best films


3d flash websites

Nelo music


3d flash websites

Nespresso


3d flash websites

InTru3D


3d flash websites

The band Dancer


3d flash websites

Fout the design


3d flash websites

This is a guest post by Ann Davlin, She is a copywriter and blogger working at MotoCMS – a company which allows you to easily create Flash website. Ann is a great fan of social media and web development trends (especially Flash), so you can always follow her on Twitter (@SmilingAnny).

Brought To You By

Premier Survey
Do you want to advertise here? Click to get more info…

May 18 2011

04:00

An Introduction To CSS3 Keyframe Animations

Advertisement in An Introduction To CSS3 Keyframe Animations
 in An Introduction To CSS3 Keyframe Animations  in An Introduction To CSS3 Keyframe Animations  in An Introduction To CSS3 Keyframe Animations

By now you’ve probably heard at least something about animation in CSS3 using keyframe-based syntax. The CSS3 animations module in the specification has been around for a couple of years now, and it has the potential to become a big part of Web design.

Using CSS3 keyframe animations, developers can create smooth, maintainable animations that perform relatively well and that don’t require reams of scripting. It’s just another way that CSS3 is helping to solve a real-world problem in an elegant manner. If you haven’t yet started learning the syntax for CSS3 animations, here’s your chance to prepare for when this part of the CSS3 spec moves past the working draft stage.

In this article, we’ll cover all the important parts of the syntax, and we’ll fill you in on browser support so that you’ll know when to start using it.

Animated-scene in An Introduction To CSS3 Keyframe Animations

A Simple Animated Landscape Scene

For the purpose of this article, I’ve created a simple animated landscape scene to introduce the various aspects of the syntax. You can view the demo page to get an idea of what I’ll be describing. The page includes a sidebar that displays the CSS code used for the various elements (sun, moon, sky, ground and cloud). Have a quick look, and then follow along as I describe the different parts of the CSS3 animations module.

(NOTE: Safari has a bug that prevents the animation from finishing correctly. This bug seems to be fixed in Safari using a WebKit nightly build, so future versions of Safari should look the same as Chrome. See more under the heading “The Animation’s Fill Mode”)

I’ll describe the CSS related to only one of the elements: the animated sun. That should suffice to give you a good understanding of keyframe-based animations. For the other elements in the demo, you can examine the code on the demo page using the tabs.

The Keyframe @ Rule

The first unusual thing you’ll notice about any CSS3 animation code is the keyframes @ rule. According to the spec, this specialized CSS @ rule is followed by an identifier (chosen by the developer) that is referred to in another part of the CSS.

The @ rule and its identifier are then followed by a number of rule sets (i.e. style rules with declaration blocks, as in normal CSS code). This chunk of rule sets is delimited by curly braces, which nest the rule sets inside the @ rule, much as you would find with other @ rules.

Here’s the @ rule we’ll be using:

@-webkit-keyframes sunrise {
	/* rule sets go here … */
}

The word sunrise is an identifier of our choosing that we’ll use to refer to this animation.

Notice that I’m using the -webkit- prefix for all of the code examples here and in the demo. I’ll discuss browser support at the end of this article, but for now it’s enough to know that the only stable browsers that support these types of animations are WebKit-based ones.

The Keyframe Selectors

Let’s add some rule sets inside the @ rule:

@-webkit-keyframes sunrise {
   0% {
      bottom: 0;
      left: 340px;
      background: #f00;
   }

   33% {
      bottom: 340px;
      left: 340px;
      background: #ffd630;
   }

   66% {
      bottom: 340px;
      left: 40px;
      background: #ffd630;
   }

   100% {
      bottom: 0;
      left: 40px;
      background: #f00;
   }
}

With the addition of those new rule sets, we’ve introduced the keyframe selector. In the code example above, the keyframe selectors are 0%, 33%, 66%, and 100%. The 0% and 100% selectors could be replaced by the keywords “from” and “to,” respectively, and you would get the same results.

Each of the four rule sets in this example represents a different snapshot of the animated element, with the styles defining the element’s appearance at that point in the animation. The points that are not defined (for example, from 34% to 65%) comprise the transitional period between the defined styles.

Although the spec is still in development, some rules have been defined that user agents should follow. For example, the order of the keyframes doesn’t really matter. The keyframes will play in the order specified by the percentage values, and not necessarily the order in which they appear. Thus, if you place the “to” keyframe before the “from” keyframe, the animation would still play the same way. Also, if a “to” or “from” (or its percentage-based equivalent) is not declared, the browser will automatically construct it. So, the rule sets inside the @ rule are not governed by the cascade that you find in customary CSS rule sets.

The Keyframes That Animate the Sun

For the purpose of animating the sun in this demo, I’ve set four keyframes. As mentioned, the code above includes comments that describe the changes.

In the first keyframe, the sun is red (as if it were just rising or setting), and it is positioned below ground (i.e. not visible). Naturally, the element itself must be positioned relatively or absolutely in order for the left and bottom values to have any effect. I’ve also used z-index to stack the elements (to make sure, for example, that the ground is above the sun). Take note that the only styles shown in the keyframes are the styles that are animated. The other styles (such as z-index and position, which aren’t animated) are declared elsewhere in the style sheet and thus aren’t shown here.

0% {
	bottom: 0; /* sun at bottom */
	left: 340px; /* sun at right */
	background: #f00; /* sun is red */
}

About one third of the way into the animation (33%), the sun is on the same horizontal plane but has risen and changed to a yellow-orange (to represent full daylight):

33% {
	bottom: 340px; /* sun rises */
	left: 340px;
	background: #ffd630; /* changes color */
}

Then, at about two thirds into the animation (66%), the sun has moved to the left about 300 pixels but stays on the same vertical plane. Notice something else in the 66% keyframe: I’ve repeated the same color from the 33% keyframe, to keep the sun from changing back to red too early.

66% {
	bottom: 340px;
	left: 40px; /* sun moves left across sky */
	background: #ffd630; /* maintains its color */
}

Finally, the sun gradually animates to its final state (the full red) as it disappears below the ground.

100% {
	bottom: 0; /* sun sets */
	left: 40px;
	background: #f00; /* back to red */
}

Associating The Animation Name With An Element

Here’s the next chunk of code we’ll add in our example. It associates the animation name (in this case, the word sunrise) with a specific element in our HTML:

#sun.animate {
	-webkit-animation-name: sunrise;
}

Here we’re introducing the animation-name property. The value of this property must match an identifier in an existing @keyframes rule, otherwise no animation will occur. In some circumstances, you can use JavaScript to set its value to none (the only keyword that has been reserved for this property) to prevent an animation from occurring.

The object we’ve targeted is an element with an id of sun and a class of animate. The reason I’ve doubled up the id and class like this is so that I can use scripting to add the class name animate. In the demo, I’ve started the page statically; then, with the click of a button, all of the elements with a particular class name will have another class appended called animate. This will trigger all of the animations at the same time and will allow the animation to be controlled by the user.

Of course, that’s just one way to do it. As is the case with anything in CSS or JavaScript, there are other ways to accomplish the same thing.

The Animation’s Duration And Timing Function

Let’s add two more lines to our CSS:

#sun.animate {
	-webkit-animation-name: sunrise;
	-webkit-animation-duration: 10s;
	-webkit-animation-timing-function: ease;
}

You can specify the duration of the animation using the animation-duration property. The duration represents the time taken to complete a single iteration of the animation. You can express this value in seconds (for example, 4s), milliseconds (2000ms), and seconds in decimal notation (3.3s).

The specification doesn’t seem to specify all of the available units of time measurement. However, it seems unlikely that anyone would need anything longer than seconds; and even then, you could express duration in minutes, hours or days simply by calculating those units into seconds or milliseconds.

The animation-timing-function property, when declared for the entire animation, allows you to define how an animation progresses over a single iteration of the animation. The values for animation-timing-function are ease, linear, ease-out, step-start and many more, as outlined in the spec.

For our example, I’ve chosen ease, which is the default. So in this case, we can leave out the property and the animation will look the same.

Additionally, you can apply a specific timing function to each keyframe, like this:

@-webkit-keyframes sunrise {
   0% {
      background: #f00;
      left: 340px;
      bottom: 0;
      -webkit-animation-timing-function: ease;
   }

   33% {
      bottom: 340px;
      left: 340px;
      background: #ffd630;
      -webkit-animation-timing-function: linear;
   }

   66% {
      left: 40px;
      bottom: 340px;
      background: #ffd630;
      -webkit-animation-timing-function: steps(4);
   }

   100% {
      bottom: 0;
      left: 40px;
      background: #f00;
      -webkit-animation-timing-function: linear;
   }
}

A separate timing function defines each of the keyframes above. One of them is the steps value, which jerks the animation forward a predetermined number of steps. The final keyframe (100% or to) also has its own timing function, but because it is for the final state of a forward-playing animation, the timing function applies only if the animation is played in reverse.

In our example, we won’t define a specific timing function for each keyframe, but this should suffice to show that it is possible.

The Animation’s Iteration Count And Direction

Let’s now add two more lines to our CSS:

#sun.animate {
	-webkit-animation-name: sunrise;
	-webkit-animation-duration: 10s;
	-webkit-animation-timing-function: ease;
	-webkit-animation-iteration-count: 1;
	-webkit-animation-direction: normal;
}

This introduces two more properties: one that tells the animation how many times to play, and an indicator that tells the animation to animate back to the start position.

The animation-iteration-count property is set to 1, meaning that the animation will play only once. This property accepts an integer value or infinite.

In addition, the animation-direction property is set to normal (the default), which means that the animation will play in the same direction (from start to finish) each time it runs. In our example, the animation is set to run only once, so the property is unnecessary. The other value we could specify here is alternate, which makes the animation play in reverse on every other iteration. Naturally, for the alternate value to take effect, the iteration count needs to have a value of 2 or higher.

The Animation’s Delay And Play State

Let’s add another two lines of code:

#sun.animate {
	-webkit-animation-name: sunrise;
	-webkit-animation-duration: 10s;
	-webkit-animation-timing-function: ease;
	-webkit-animation-iteration-count: 1;
	-webkit-animation-direction: normal;
	-webkit-animation-delay: 5s;
	-webkit-animation-play-state: running;
}

First, we introduce the animation-delay property, which does exactly what you would think: it allows you to delay the animation by a set amount of time. Interestingly, this property can have a negative value, which moves the starting point partway through the animation according to negative value.

The animation-play-state property, which might be removed from the spec, accepts one of two possible values: running and paused. This value has limited practical use. The default is running, and the value paused simply makes the animation start off in a paused state, until it is manually played. You can’t specify a paused state in the CSS for an individual keyframe; the real benefit of this property becomes apparent when you use JavaScript to change it in response to user input or something else.

The Animation’s Fill Mode

We’ll add one more line to our code, the property to define the “fill mode”:

#sun.animate {
	-webkit-animation-name: sunrise;
	-webkt-animation-duration: 10s;
	-webkit-animation-timing-function: ease;
	-webkit-animation-iteration-count: 1;
	-webkit-animation-direction: normal;
	-webkit-animation-delay: 5s;
	-webkit-animation-play-state: running;
	-webkit-animation-fill-mode: forwards;
}

The animation-fill-mode property allows you to define the styles of the animated element before and/or after the animation executes. A value of backwards causes the styles in the first keyframe to be applied before the animation runs. A value of forwards causes the styles in the last keyframe to be applied after the animation runs. A value of both does both.

UPDATE: It seems that the animation-fill-mode property has been removed from the spec, or else was never there to begin with, so this property may not end up in the spec. Also, Chrome and Safari respond differently when it is used. Safari will only apply a value of “forwards” if there are exactly two keyframes defined. It always seems to use the 2nd keyframe as the “forwards” state, which is not how Chrome does it; Chrome uses the final keyframe, which seems to be correct behaviour. Additionally, I’ve confirmed that the most up to date WebKit nightly does not have this bug, so future versions of Safari will render this correctly.

Shorthand

Finally, the specification describes shorthand notation for animations, which combines six of the properties described above. This includes everything except animation-play-state and animation-fill-mode.

Some Notes On The Demo Page And Browser Support

As mentioned, the code in this article is for animating only a single element in the demo: the sun. To see the full code, visit the demo page. You can view all of the source together or use the tabs in the sidebar to view the code for individual elements in the animation.

The demo does not use any images, and the animation does not rely on JavaScript. The sun, moon and cloud are all created using CSS3’s border-radius, and the only scripting on the page is for the tabs on the right and for the button that lets users start and reset the animation.

If you view the page in anything but a WebKit browser, it won’t work. Firefox does not currently support keyframe-based animation, but support is expected for Firefox 5, and the -moz-based syntax for animations is supported in the latest Aurora build. So, to make the source code as future-proof as possible, I’ve included all of the -moz prefixes along with the standard syntax.

Here are the browsers that support CSS3 keyframe animations:

  • Chrome 2+,
  • Safari 4+,
  • Firefox 5+,
  • iOS Safari 3.2+,
  • Android 2.1+.

Although no official announcement has been made, support in Opera is expected. There’s no word yet on support in IE.

Further Reading

(al) (vf) (il)


© Louis Lazaris for Smashing Magazine, 2011. | Permalink | Post a comment | Smashing Shop | Smashing Network | About Us
Post tags: animation, CSS, keyframe

September 21 2010

12:00

Animating With Firefox’s mozRequestAnimationFrame

Firefox 4 is going to be a very exciting release. Robert O'Callahan details one of the new features, which should help animation, called mozRequestAnimationFrame. First the motivation:

In Firefox 4 we've added support for two major standards for declarative animation --- SVG Animation (aka SMIL) and CSS Transitions. However, I also feel strongly that the Web needs better support for JS-based animations. No matter how rich we make declarative animations, sometimes you'll still need to write JS code to compute ("sample") the state of each animation frame. Furthermore there's a lot of JS animation code already on the Web, and it would be nice to improve its performance and smoothness without requiring authors to rewrite it into a declarative form.

setTimeout and setInterval can only go so far; as Robert describes, we sometimes need something between purely JavaScript-driven animation using setTimeout and having to go full declarative using CSS3 or SMIL. mozRequestAnimationFrame is one potential way to get better synchronization and performance from JavaScript based animation.

Some sample code from Robert using it:

JAVASCRIPT:
var start = window.mozAnimationStartTime;
function step(event) {
   var progress = event.timeStamp - start;
   d.style.left = Math.min(progress/10, 200) + "px";
   if (progress &lt;2000) {
      window.mozRequestAnimationFrame();
   } else {
      window.removeEventListener("MozBeforePaint", step, false);
   }
}
window.addEventListener("MozBeforePaint", step, false);
window.mozRequestAnimationFrame();
 

It's not very different from the usual setTimeout/Date.now() implementation. We use window.mozAnimationStartTime and event.timeStamp instead of calling Date.now(). We call window.mozRequestAnimationFrame() instead of setTimeout().

Note that you will generally get about 50 frames per second using mozRequestAnimationFrame. As Robert describes in another blog post, this is a feature not a bug:

On modern systems an application usually cannot get more than 50-60 frames per second onto the screen...So even if an application updates its window 100 times a second, the user won't be able to see more than about half of those updates...firing a MozBeforePaint event more than about 50 times a second is going to achieve nothing other than wasting CPU (i.e., power). So we don't. Apart from saving power, reducing animation CPU usage helps overall performance because we can use the free time to perform garbage collection or other house-cleaning tasks, reducing the incidence or length of frame skips.

I hope that other browsers pick up this feature.

September 13 2010

11:00

Animated CSS3 cube using 3D transforms

I've been doing alot of experimenting with HTML5/CSS3 on the iPhone doing animation, and I've been surprised with the low frame rate of animating through Canvas or SVG. If you are trying to do animation, especially 3D, on the iPhone it seems like the name of the game is to it through the GPU, and the only way to do that these days on iOS is CSS3 Animations/Transitions/3D.

These experiments caused me to stumble on Paul Hayes interesting work simulating a 3D animated cube using CSS3, hence they happen on the GPU on the iPhone/iPad and are quite fast:

A 3D cube can be created solely in CSS, with all six faces. Using JavaScript to detect key presses and update inline styles this cube can be intuitively navigated.

Demo (Webkit only)

Paul achieves this by having each face of the cube be a unique DIV, each with a 'face' class and inside of a larger 'cube' class all wrapped by an 'experiment' class:

HTML:
<div id="experiment">
        <div id="cube">
                <div class="face one">
                        One face
                </div>
                <div class="face two">
                        Up, down, left, right
                </div>
                <div class="face three">
                        Lorem ipsum.
                </div>
                <div class="face four">
                        New forms of navigation are fun.
                </div>
                <div class="face five">
                        Rotating 3D cube
                </div>
                <div class="face six">
                        More content
                </div>
        </div>
</div>
 

The outer wrapper is the camera and allows you to apply perspective and where you want the perspective origin to be:

CSS:
#experiment {
    -webkit-perspective: 800;
    -webkit-perspective-origin: 50% 200px;
}
 

The #cube itself is given a size, CSS transition properties so things will animate nicely, and an instruction to preserve 3D children and not 'flatten' them:

CSS:
#cube {
    position: relative;
    margin: 0 auto;
    height: 400px;
    width: 400px;
    -webkit-transition: -webkit-transform 2s linear;
    -webkit-transform-style: preserve-3d;
}
 

Each of the faces is given some common styling:

CSS:
.face {
    position: absolute;
    height: 360px;
    width: 360px;
    padding: 20px;
    background-color: rgba(50, 50, 50, 0.7);
}
 

The individual face DIVs are then rotated and translated in 3D space into their correct positions:

CSS:
#cube .one {
      -webkit-transform: rotateX(90deg) translateZ(200px);
    }

    #cube .two {
      -webkit-transform: translateZ(200px);
    }

    #cube .three {
      -webkit-transform: rotateY(90deg) translateZ(200px);
    }

    #cube .four {
      -webkit-transform: rotateY(180deg) translateZ(200px);
    }

    #cube .five {
      -webkit-transform: rotateY(-90deg) translateZ(200px);
    }

    #cube .six {
      -webkit-transform: rotateX(-90deg) translateZ(200px) rotate(180deg);
    }
 

Read more in Paul's post.

September 12 2010

13:56

Eye-Candy For The Weekend: Particle Animation Music Videos

Smashing-magazine-advertisement in Eye-Candy For The Weekend: Particle Animation Music VideosSpacer in Eye-Candy For The Weekend: Particle Animation Music Videos
 in Eye-Candy For The Weekend: Particle Animation Music Videos  in Eye-Candy For The Weekend: Particle Animation Music Videos  in Eye-Candy For The Weekend: Particle Animation Music Videos

Just like a couple of weeks ago, this weekend again we’ve got something unusual and creative to lift up your spirits and challenge your creativity over a lousy Sunday. Particle animation is a beautiful concept from motion graphics. Using specialized software, you can simulate the movements of particles depending on the environment — for instance, music rhythm.

In today’s post we present selected particle animation music videos. Be prepared: the page may take a while to load. Please make sure to visit the sources of videos to enjoy the viewing experience in HD, and don’t forget to turn on your hi-fi-system. We also feature some tutorials in the end of this post: and here you go — now you have something fun to do over the weekend!

[Offtopic: by the way, did you know that there is a Smashing eBook Series? Book #1 is Professional Web Design, 242 pages for just $9,90.]

Beautiful Particle Animation Videos

Max TV Color Artist

Fire Flower by Pierre Michel

Procedural Particles from Matthias Müller

Audio visual Halo

We Own The Sky

Solar, with lyrics.

Vestige – Siggraph CAF 2009 Opening version

VITAL “Airport”

Particle Garden

Particle Objects

Particle Monster

Let yourself feel

SPIRE / Corporate Identity Launch Video

Particle art

Weird Fishes: Arpeggi

The stars are projectors

Red Smoke – Particle animation to Music

Particle Visualisation

Particle Playground

Tutorials and Further Resources

Particle Animation to Music
This tutorial is a detailed example of visualizing music through the formation of particles.

Extensive Guide For Particle Animation
An extensive guide for working with Trapcode Suite to generate videos with animated particles.

Solar, with lyrics
This tutorial will lead you to the process of particle animation created with Processing, audio by Goldfrapp.

How To Create A Surreal Outer Space Nebula
An impressive tutorial on creating a surreal outer space nebula provides you with the details regarding particle animation synchronized with music.

Particle Explosion
In this tutorial you will learn how to build a complex particle system using CC Particle World and Synchronize the particle blast to shatter a title.

Building Up Particles
This tutorial demonstrates the creation process of particles to simulate a disintegrating hot air balloon using Trapcode Particular and Adobe After Effects.

Make a Particle Explosion Effect
The author of this tutorial has broken down the process of developing an in-game particle effect into a series of steps. This technique is mostly used for a particle explosion effect in a video game.

Trapcode Gallery on Vimeo
A user-submitted gallery of videos created with Trapcode Suite.

iPhone App – Magnetosphere
This iPhone app helps you create particle animation easily.

Particle Animation Software
A detailed overview of various particle animation applications, with ratings, reviews and screenshots.

Last Click

Particle collection
A remarkable collection of various particle animation effects from Matthias Müller.

Would you like to see more similar posts on SM on weekends?



Would you like to see more similar posts on SM on weekends?online surveys


© Bhanu Ahluwalia for Smashing Magazine, 2010. | Permalink | Post a comment | Add to del.icio.us | Digg this | Stumble on StumbleUpon! | Tweet it! | Submit to Reddit | Forum Smashing Magazine
Post tags: animation, Graphics, Inspiration, motion, video

August 24 2010

10:00

Blow Things Up!

Jonas Wagner has ported the Flash 2D physics engine Box2DFlash to JavaScript:

In his demo Jonas uses the Canvas tag to map the physics simulations on. Click on it to create explosions:

Jonas talks about the approach he used to convert the original library from ActionScript to JavaScript:

At first I thought this conversion would be trivial as both actionscript and javascript are dialects of ECMAScript. Well, I was wrong. Nevertheless I continued to follow my regex based approach, basically trying to ram my head through a wall. After a few attempts I succeeded to convert Box2DAS3 to javascript. It had a nasty bug though. Two solid cubes were able to penetrate each other when they fell on their edges. The reason? ActionScript supports 'properties'. I didn't know about this and the conversion script does not support it. In the end I fixed the few properties in the translated code by hand because I was too lazy to add support for getters and setters to the conversion script. Now it seems to work pretty well. Please keep in mind, this is not a generic actionscript to javascript compiler, it's just a script that happens to work for box2dflash.

The explosions in the demo are simulated by shooting out a few tracer particles with a high density and velocity. The benefit over just applying an impulse to each object is that the strength of the impulse is proportional to the surface area. Also the force of the explosion will to some extent be redirected to the side by the floor. When using this in production code you would probably want to destroy the tracer particles after their first collision or a few seconds.

You can grab the converted JavaScript yourself. There isn't any current documentation but you can follow the existing Flash box2dflash documentation.

Here's what the explode function looks like in Jonas' test demo for example:

JAVASCRIPT:
function explode(x, y) {
    var ntracer = 25;
    while(explosionParticles.length){
        world.DestroyBody(explosionParticles.pop());
    }
    for(var i = 0; i <ntracer; i++) {
        var a = Math.PI/ntracer*2*i;
        var vx = Math.cos(a);
        var vy = Math.sin(a);
        var bodyDef = new b2BodyDef();
        bodyDef.position.Set(x+vx, y+vy);
        bodyDef.isBullet = true;
        var body = world.CreateBody(bodyDef);
        var shapeDef = new b2CircleDef();
        shapeDef.radius = 0.1;
        //var shapeDef = new b2PolygonDef();
        //shapeDef.SetAsBox(1.0, 1.0);
        shapeDef.restitution = 0.0;
        shapeDef.density = 5000.0/ntracer;
        shapeDef.friction = 0.0;
        body.CreateShape(shapeDef);
        body.SetMassFromShapes();
        body.ApplyImpulse({x: vx*500, y:vy*500}, {x:x, y:y});
        body.w = 1.0;
        body.h = 1.0;
        explosionParticles.push(body);
    }
}
 

This library is useful for games and fancy user interfaces using HTML5.

[via Mr. Doob]

June 14 2010

22:36

animateWithCSS: Aza’s jQuery Plugin

JAVASCRIPT:
// Makes all paragraph elements grow a border and then atrophy away.
$("p").animateWithCSS(
  {border: "5px solid #555"}, // CSS properties to animate
  1000,                       // Duration in ms
  "cubic-bezier",        // The timing function
  function() {              // Callback
    $("p").animateWithCSS({border: "0px"}, 350);
  }
);
 

Above is an example of Aza Raskin's jQuery plugin that sits on top fo CSS transforms.

The code renders this:

What is maybe even more interesting, is the critique into CSS transitions:

Better timing functions. While using a cubic bezier curve is clever—it packs a lot of variation into just four numbers—it isn’t enough. While I was able to create a basic bounce animation, not only does the spec explicitly disallow it, but I can’t control even the basic parameters of the bounce (like how fast it returns). As John Resig mentioned in a blog post, it would be nice to supply a custom Javascript timing function (although this might break the ability to do hardware acceleration). A more CSS-like solution might be to allow authors to provide an arbitrary number of control points for a series of linked quadratic or cubic bezier curves (and to not restrict the y-axis points to the 0 to 1 range). That would enable fine-grained control of timing without requiring Javascript.

Ability to layer two animations on top of each other. If I’ve started an animation moving an element to the left, and half-way through want to start animating its opacity at a different rate, things get complicated very quickly. And by complicated, I mean impossible.

Ability to register an on step handler. We can currently register a “transitionend” event handler. I’d like to be able to do the same for “transitionstep”. This would make CSS Transitions potentially much more versatile—and allow frameworks to keep innovating on top of the transitions base instead of reverting to pure Javascript animation.

June 09 2010

21:00

Add Motion To Website: jQuery Animation Plugins From 2010

In our niche it’s very important to be up to date with latest technologies and features available to impress new clients, show of in portfolio and add functionality more easily – using some advanced code snippets, plugins or hacks.

jQuery possibilities are growing rapidly and there are many people who play with code and discover some amazing combinations achieving effects you have never seen before!

You will find here many plugins which will help to add motion, 3d effects and animation to your website! This list will blow your mind away with possibilities – ready?!!!

1. AJAX-ZOOM – Image Zoom – Pan Gallery plugin

AJAX-ZOOM is a sophisticated image zoom & pan gallery plugin based on jQuery and PHP. With over 250 options it is very flexible and can be integrated into any website.

Download Now | View Examples

2. Image Rotator

Simply rotates an image by a certain degree or allows the user to rotate an image by dragging around a central axis.

Download Now | View Example

3. Cloud Zoom

The Cloud Zoom plugin is comparable to commercial image zoom products such as Magic Zoom. Compared to the popular jQZoom plugin, Cloud Zoom is smaller, has more features and more robust compatability across browsers.

Download Now | View Example

4. jQuery Before/After Plugin

Download Now | View Example

5. jQDock

Transform a set of images into a Mac-like Dock menu, horizontal or vertical, with icons that expand on rollover, and optional labels.

Download Now | View Example

6. Visual Lightbox – Create fantastic lightbox-style galleries and slideshows. jQuery LightBox Plugin.

Download Now | View Examples

7. Image Bubbles

Image Bubbles is a cool Flash-like effect that causes an image to bubble up and expand whenever the mouse rolls over it from within a series of images.

Download Now | View Example

8. jQuery Panel Magic

jQuery Panel Magic is a new take on website navigation. Using a matrix or grid style layout for your website, you can easily implement this plugin for small websites and web applications. It gives you more room for your design and provides a cool new approach to a sitemap.

Download Now | View Example

9. iCheckbox

Convert a checkbox or multiple checkboxes into iphone style switches.

Download Now | View Example

10. jqFancyTransitions

jqFancyTransitions is plugin for displaying your photos as slideshow with fancy transition effects.

Download Now | View Example

11. Images In All Size jQuery Plugin

Download Now | View Example

12. Text Effects

Download Now | View Examples

13. jCoverflip

jCoverflip is a jQuery cover flow widget that allows website administrators to present featured website content in a visually appealing manner. The widget is quick setup and is highly configurable, and can run as a Drupal Module or standalone.

Download Now | View Example

14. BxSlider

bxSlider is a jQuery content slider plugin that is light weight and easy to use.

Download Now | View Example

15. jScratchcard plugin

Download Now | View Example

16. jQuery Menu Style 1 – Drop Down Menu with Visual Effects

View Examples

17. Frame Animation Plugin for jQuery

Download Now | View Example

18. Cusor Hover Buttons

This plugin lets you create a two-layer button with one layer that follows the mouse. This method allows you to create some very professional effects on your site.

Download Now | View Example

19. jQuery carrousel

The core allows to create your own controls or effects. This plugin transform an “ul li” into an animated carrousel.

Download Now | View Example

20. 2D Transform

This plug-in utilizes the matrix filter in IE and the new CSS3 transform properties to 2d transform any DOMElement.

Download Now | View Example

21. jPhotoGrid

This plugin displays a list of image thumbnails in a grid and allows them to be zoomed open. It’s a cool and simple effect.

Download Now | View Example

22. jMagnify

jQuery jMagnify, plugin attach a ola effect to some text following the mouse position.

Download Now | View Examples

23. animaDrag: Animating Drag and Drop Plugin

Download Now | View Example

24. jOla

Download Now | View Example

25. Flight Board

This plugin sets a division to flip between text messages like a flight board at an airport. It alternates between two or more messages by flipping individual characters.

Download Now | View Example

26. 3D Cloud Carousel

This is a fast and cross-browser implementation of a 3d carousel – looks very nice, more like a Flash implementation. It can create dynamic reflections underneath the carousel items, is accessible and degrades nicely without JavaScript.

Download Now | View Example

27. 3D Feature Image Carousel

This plugin rotates images in a three dimensional (simulated) carousel. Optionally, all images can have a description element attached to them that pops up on an overlay whenever that image rotates to the center.

Download Now | View Example

28. Smooth Anchors jQuery Plugin

This plugin creates a simple animation for anchor links by quickly scrolling the page to the area where the anchor is at rather than just jumping right to the anchor like normal.

Download Now | View Example

29. HoverAttribute

HoverAttribute is a jQuery plugin that allows you to make (link-)elements more dynamic by making an attribute of that element show up on hovering.

Download Now | View Example

30. Expanding Grid

Creates grid system out of divs. On hover the active grid expands to ratio set by the config, fades out the background.

Download Now | View Example

May 28 2010

10:41

Rounded corners. Moving.

Chris Vanrensburg: “In a similar vein to a recent experiment with animating position, I wanted to see how curves could be applied to animating size changes for an object. To be expected, applying different interpolation curves for the width and height CSS style properties produces some fun effects (to be seen towards the bottom of the list of presets).”

The Web 2.0 crowd love their rounded corners. How about animating them! This is where Chris takes his latest experiment. Click around in the demo area and watch the smooth effects.

February 28 2010

10:00

50 Awesome Animations made with CSS3

CSS3 has brought some amazing new features. And the most fun is playing with the CSS animation. Here is a compilation of 50 CSS3 animation that allows you to perform many motion-based functions normally Delegated to JavaScript. In order to view this effect, you are required to have WebKit browsers like Safari and Chrome ( very sorry for the users of Internet Explorer )

1. CSS3 Clock With jQuery

Use the basic features of the CSS3 Transform: rotate. And the combination of javascript frameworks like jQuery can produce a cool CSS3 clock

2. Analogue Clock

Analogue clock created using webkit transition and transform CSS. JavaScript is only used to pull in the current time.

3. 3D Cube That Rotates Using Arrow Keys

You can Use up, down, left and right keys to navigate the 3D cube. 3D cube built using -webkit-perspective, -webkit-transform and -webkit-transition.

4. Multiple 3D Cubes (Slide In/Out)

Multiple 3D Cubes using CSS3 and proprietary ‘transform’ and ‘transition’ properties. I thought it was amazing, you can see the writing on the 3D object.

5. CSS3 Accordion

An accordion effect using only CSS. Proprietary animation in WebKit based browsers.

6. Auto-Scrolling Parallax

Auto-Scrolling Paralax is an animated parallax effect using WebKit’s CSS transition property,Auto-Scrolling Paralax no need JavaScript

7. Isocube

Isocube is like 3DCube but have litle different. Isocube can load images on one side

8. Image Gallery

9. Matrix

The Matrix is one of the best sci-fi films of all time. CSS3 capable of making such an amazing animated film made

10. 7 Javascript-effect Alternatives Using CSS3

7 examples of alternatives to javascript effect by using CSS3. Various effects such as Fade Block, Block Pulsate, Nudge, Expand Block, Block Bounce, Spin Block and Accordion

11. Image Hover Effects

Image Hover Effects is an example of using CSS to replace the javascript. The image will shrink when you put your mouse pointer on top of it.

12. Turning Coke Can (Control With Scrollbar)

13. 3D Meninas

14. Polaroid Gallery

Polaroid Gallery is animated pile of photographs utilizing a ton of new CSS3 commands. It’s interesting when your mouse cursor is above the image, the image will enlarge

15. Space

16. Mac Dock

This list of links as the basis and change into an OS X icon dock of amazing.

17. Drop-In Modals

With CSS3 effects and property Drop In Modals can help you make quick, animation, a simple change to using modals, and some subtle design cues.

18. Sliding Vinyl

Vinyl effect can be created by using CSS3 transition and a little HTML. This can make a standard album cover to have an interesting style

19. Zooming Polaroids

Polaroid is a picture that is in the box and spun like a pile of random photos that are sorting through CSS3 techniques. The text that comprises only extract the title and alt attribute

20. Animated Rocket

The principle of Animatid Roket is CSSEffect. The transformation changed the appearance of an element in the browser, moving, rotating, or other means. In determining the conversion of styles before making the application to happen so that you can not really animation.

21. Poster Circle

Poster Circle. is an animated spin column consists of a row of colored boxes and text are wonderful. The overall effect is crazy cool and undeniably dizzying

22. Morphing Cubes

Morphing Cubes will shows some of the more interesting content using 3D transformations, animations and transitions. Note that you can still select text in the element, even if the rotation. Converting elements are fully interactive.

23. Animated Polaroid Gallery

This is the example of other Polaroid Gallery. Piles of images at random and when the cursor hovers over an image, selected images will be enlarged

24. Spotlight Cast Shadow

When the cursor moves as if like a lamp spotlight leading up to the writing and cast

25. Colorful Clock

Colorful Clock is a colorful jQuery & CSS3 which will help you keep track of those precious last seconds of the year.

26. Lightbox Gallery

Lightbox Gallery is an awesome image gallery which leverages the latest CSS3 and jQuery techniques.Lightbox Gallery using jQuery, jQuery UI (for the drag and drop) and the fancybox jQuery plugin for the lightbox display in addition to PHP and CSS for interactivity and styling.

27. Elastic Thumbnail Menu

Elastic Thumbnail Menu is an alternative method for smoothing the menu, in particular by increasing the menu items when the mouse is hovering over the menu. And then expand to the top menu

28. Coverflow

This animation Apple style that combines CSS transformation and jqueryUI. This one truly animate between two half states, making a slider like iTunes

29. jQuery DJ Hero

DJ Hero This is one of the interesting combination of CSS3 with jquery. On-screen controls you can control the pace or just take enough to record your mouse

30. Dynamic Stacking Cards

inn is a dynamic stack of index cards that simply using HTML and CSS3 features such as change and transition (for the dynamic effects) and the @ font-face, box-shadow and border-radius (for styling).

31. Another Image Gallery

This is an example of another image gallery that uses CSS3 transforms property and property transitions.

32. Snow Stack (Control With Arrow Keys)

33. Animated Pricing Column

CSS3 animation can also be used in the package list price of a product. Animated Column Pricing can be applied properly there

34. Slick jQuery Menu

Slick Jquery Menu achieved through a combination of CSS3 and JQuery menu below is very elegant and shows some great use of Jquery and CSS3. This is just one of those crazy concepts that the test can be used in CSS3 will be true of the standard Web.

35. CSS Tabs Without Javascript

36. Tab Menus Without Javascript

37. SVG Fisheye Menu

CSS animation can animate almost any property on the item and do funny things, such as rotation and tilt. As proof,will created quick and dirty CSS3 Fisheye / Dock demo. Used as an added bonus, the demo-SVG in the tag IMG.

38. Falling Leaves

Like autumn. Animated falling leaves are made using CSS3

39. Rotating Gallery

Image Gallery Rotaitng build with CSS transform transition and CSS features. To see the effects of rotation, click the small image

40. Dropdown Menu

Dropdown Menu is a very nice navigation menu by using CSS3 transition property. CSS transitions are very strong influence to renounce the use of JavaScript for many common side effects.

41. Star Wars Crawl

Star Wars opening crawl, using only HTML & CSS. It only works in Snow Leopard in Safari 4.0.4 and the WebKit nightly.

42. Sticky Notes

43. Snowflakes

44. Another Fisheye

This is another fisheye that using CSS3

45. Frame-by-Frame Animation

The first demonstration reqires you to keep clicking the image to see the next frame, and it wraps around to the start when you reach the last frame.The second demonstration just needs you to keep the mouse moving over the image in MOST browsers. But the BIG drawback to this method is that the speed of movement of the mouse governs the speed of animation

46. AT-AT Walker

AT-AT Walker is not flash but only CSS3. That amazing !

47. Another Accordion

48. Dynamic Presentation Without Flash

49. Smoothie Slider Menu

50. Spinner

This is basically like an ajax/loader spinner except its not a animated gif. It uses CSS3 to make it spin.

Related posts:

  1. 33 Must Read CSS3 Tips, Tricks, Tutorial Sites and Articles
  2. 30 Stylish jQuery Tooltip Plugins For Catchy Designs
  3. 22 Advanced CSS Text Effects And Web Typography Tips
  4. 300+ Jquery, CSS, MooTools and JS navigation menus
  5. 7 Awesome WordPress Plugins To Give Your Dashboard A New Look

Older posts are this way If this message doesn't go away, click anywhere on the page to continue loading posts.
Could not load more posts
Maybe Soup is currently being updated? I'll try again automatically in a few seconds...
Just a second, loading more posts...
You've reached the end.

Don't be the product, buy the product!

Schweinderl