Creating a Puzzle game using jQuery

Today we are making a simple puzzle game called “Doraemon Puzzle”. The purpose of the game is to slide 15 square blocks around to form an image. The goal of this tutorial is to look at this simple browser-based game and explain how it was made line by line. It’s a great way to learn jQuery. For this tutorial, We will use a 2D image of kid’s favorite cartoon “Doraemon” for square-sliding game.  I will go over each line of code to demonstrate the train of thought. I really do believe that breaking this game up into explanations on per-line basis will help you understand how to use jQuery in your own projects.

Concept about creating a Game as a jQuery Plugin

A jQuery plugin is a perfect way to create image slideshows, custom user interface controls and of course browser-based games. We won’t just write JavaScript code here, we will create a jQuery plugin.

A plugin is nothing more than our own custom jQuery method. You know how we have jQuery’s methods .css() and .animate()? Well, jQuery gives us the ability to extend its own functionality with custom methods that we create ourselves. Like the existing jQuery methods, we can apply the method we will create to a jQuery selector.

Well, the game is called “Doraemon Puzzle”, and we want to make our game “embeddable” inside an arbitrary HTML element like <div id=”game_area”>here</div> so we can move it around anywhere on the page.

creating-puzzle-game-with-jquery

The jQuery

We will actually create our own jQuery method and call it .puzzle_dg(). I have already created the plugin “puzzle_dg.min.js“.  Therefore, in order to launch the game inside an HTML element with id “#game_area” we will call this command:

$(window).load(function(){
    $('#game_area').puzzle_dg(140)
});

This will create and attach the game board to the div whose id is “game_area.” Also, each square will become 140 by 140 pixels in width and height based on the only passed parameter. You can re-size the game blocks and area easy by just changing this parameter.

In this tutorial I used the image of a Doraemon cartoon. You can replace it with any image you want.

Executing a custom method as shown in the code above will pass the selector string “#game_area” to our plugin function which grabs the DIV. Inside our custom method, we can refer to that selector/element using the this keyword. And we can also enable jQuery methods on it by passing it to the new jQuery object like so: $(this); — inside the extended function I have created.

The HTML

First, let’s prepare HTML markup for our game.  We have only call <div id="game_area"></div> for creating game area.

We have to include the awesome jQuery library. After including the jQuery library we have to include “puzzle_dg.min.js”  file as game plugin.

<!-- This is where the game will be injected -->
<div id="game_object"></div>

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">$(window).load(function(){
    $('#game_area').puzzle_dg(140)
});</script>

CSS

There are a few styles for our game:

#game_area {
	background-color: #ffffff;
	height: 550px;
	margin: 20px auto;
	position: relative;
	width: 550px;
}
#board div {
	background: url("images/doraemon.jpg") no-repeat scroll 0 0 #ffffff;
	cursor: pointer;
	height: 140px;
	line-height: 140px;
	position: absolute;
	text-align: center;
	width: 140px;
	/* css3 shadow */
    -moz-box-shadow: inset 0 0 20px #2caae7;
	-webkit-box-shadow: inset 0 0 20px #2caae7;
	-ms-box-shadow: inset 0 0 20px #2caae7;
	-o-box-shadow: inset 0 0 20px #2caae7;
	box-shadow: inset 0 0 20px #2caae7;
}

view demo

Conclusion

I tried to explain the code to the best of my ability here but some details were skipped because there is so much more to JavaScript. I hope you enjoyed this article. Thanks for reading!

You may like:

Posted by: Dhiraj kumar

Animate Full-Page Multiple Background images with fade-in & fade-out effect – jQuery

“How to change multiple background-image of body with effects?” – I think this is a major problem which all designers face. You can fade background colors but not background images. The way to work around this is to have your images as <img> tags and hide them by default display:none;. Give your images position:absolute and z-index:-1 so they act like backgrounds and are behind everything else.

Here’s a quick example of multiple images fading one after the other.

jquery-full-page-animated-background-images

The HTML

Html is very simple. Just add a div with multiple images which you want to animate / change in background with fade effects.

<div id="wrap">
<img class="bgfade" src="http://farm9.staticflickr.com/8526/8668341950_182b74faf2_z.jpg">
<img class="bgfade" src="http://farm9.staticflickr.com/8532/8667337535_6da0a9a261_z.jpg">
<img class="bgfade" src="http://farm9.staticflickr.com/8540/8667244539_d227f8c435_z.jpg">
</div>

The CSS

Now, We will use some CSS Technique which will create an illusion like background-image animation. The way to work around this is to have your images as <img> tags and hide them by default “display:none;”. Give your images “position:absolute” and “z-index:-1” so they act like backgrounds and are behind everything else. Now, set css property of div#wrap which includes these images to “position:fixed” and “top:0; left:0;” so that it will fix with page background.

#wrap{
	position:fixed;; 
	z-index:-1; 
	top:0; 
	left:0; 
	background-color:black
}
#wrap img.bgfade{
	position:absolute;
	top:0;
	display:none;
	width:100%;
	height:100%;
	z-index:-1
}

jQuery

Now, it is java-script’s turn. We will calculate browser window’s height & width. After that we will set width/height of div#wrap to browser so that background cover entire webpage. Now we have to animate our images. We will simple use function of fadeIn() and fadeOut() in images for this.

$(window).load(function(){
$('img.bgfade').hide();
var dg_H = $(window).height();
var dg_W = $(window).width();
$('#wrap').css({'height':dg_H,'width':dg_W});
function anim() {
    $("#wrap img.bgfade").first().appendTo('#wrap').fadeOut(1500);
    $("#wrap img").first().fadeIn(1500);
    setTimeout(anim, 3000);
}
anim();})
$(window).resize(function(){window.location.href=window.location.href})

Updated

I have updated the script. Actually, after re-sizing the browser we have to update the width/height of div#wrap. So, I am going to reload this window, when ever browser will re-size. It will help to re-calculate all these and refresh the animation. Div#wrap will re-size according to browser window and play animation smoothly.

view demo

You may like:

Posted by: Dhiraj kumar

Responsive jQuery Banner Slider with Pagination circles – Responsive_DG_Slider

After working on Responsive_DG_Slider,  which is a most flexible/responsive image slider with different random transition effects. After full-screen example, I am sharing another example with different transition effects. It is very easy to implement.

Here I am showing It’s Pagination circles with the height relative to the width functionality powered by the fantastic java-script library jQuery.

Configuring Your Slider

As we have done earlier, configuring the slider is very simple, you just need to place your images and call the initializer function and your slider is ready. Here’s how you can do this for liquid/responsive images slider with pagination.

responsive-slider-pagination-circle

The HTML

<div class="fluid_container">
        <div class="fluid_dg_wrap fluid_dg_charcoal_skin" id="fluid_dg_wrap_1">
            <div data-thumb="slides/thumbs/1.jpg" data-src="slides/1-1280x720.jpg">
                <div class="fluid_dg_caption fadeFromBottom">
                    Responsive_DG_Slider is a responsive/adaptive slideshow. <em>Try to resize the browser window</em>
                </div>
            </div>
            <div data-thumb="slides/thumbs/2.jpg" data-src="slides/2-1280x720.jpg">
                <div class="fluid_dg_caption fadeFromBottom">
                    It uses a light version of jQuery mobile, <em>navigate the slides by swiping with your fingers</em>
                </div>
            </div>
            <div data-thumb="slides/thumbs/3.jpg" data-src="slides/3-1280x720.jpg">
                <div class="fluid_dg_caption fadeFromBottom">
                    <em>It's <strong>completely free</strong>, with tons of effects, Prev / next, pager, Start / Stop / Auto control controls and lot of customizable options.</em>
                </div>
            </div>
            <div data-thumb="slides/thumbs/4.jpg" data-src="slides/4-1280x720.jpg">
                <div class="fluid_dg_caption fadeFromBottom">
                    Responsive_DG_Slider slideshow provides many options <em>to customize your project</em> as more as possible
                </div>
            </div>
            <div data-thumb="slides/thumbs/5.jpg" data-src="slides/5-1280x720.jpg">
                <div class="fluid_dg_caption fadeFromBottom">
                    It supports captions, HTML elements and videos and <em>it's validated in HTML5</em> (<a href="http://validator.w3.org/check?uri=http%3A%2F%2Fdemo.web3designs.com%2FResponsive_DG_Slider%2Fresponsive-slider-pagination-circle.htm" target="_blank">have a look</a>)
                </div>
            </div>
            <div data-thumb="slides/thumbs/6.jpg" data-src="slides/6-1280x720.jpg">
                <div class="fluid_dg_caption fadeFromBottom">
                    Different color skins and layouts available, <em><a href="http://demo.web3designs.com/Responsive_DG_Slider/fullscreen-responsive-image-slider.htm">fullscreen</a> ready too</em>
                </div>
            </div>
        </div>
    </div>

The CSS

First we have to link it’s default css file.

<link rel='stylesheet' id='fluid_dg-css'  href='css/fluid_dg.css' type='text/css' media='all'>

Now some customization:

.fluid_container {
			margin: 0 auto;
			width: 100%;
		}

The jQuery

First, We have to add some jQuery library.

 <script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.min.js'></script>
    <script type='text/javascript' src='Scripts/jquery.mobile.customized.min.js'></script>
    <script type='text/javascript' src='Scripts/jquery.easing.1.3.js'></script> 
    <script type='text/javascript' src='Scripts/fluid_dg.min.js'></script>

After adding all these library we have to initiate the Responsive_DG_Slider.

jQuery(document).ready(function(){
		jQuery(function(){			
			jQuery('#fluid_dg_wrap_1').fluid_dg({thumbnails: true,height:"25%"});
		}); })

You have done!!

Now enjoy your liquid slider. Please feel free to comment and share your thoughts/ideas about the result.
view demo

Updated

APIs and other options of this wonderful plugin, please click here.

You may like:

Posted by: Dhiraj kumar

Full-Screen Responsive jQuery Banner Slider – Responsive_DG_Slider

After working on responsive or flexy designs, I found some serious issues about fixed width in most of images/banner sliders which I have got online. So, I thought to develop a liquid/responsive images slider with different transition effects. Here, I am going to introduce you, a most flexible/responsive slider i.e. Responsive_DG_Slider. It is so easy and useful. I have decided that I will post a page dedicated to this slider with it’s features and API later.

Here I am showing It’s full screen responsive image slider functionality powered by the fantastic java-script library jQuery. With a nice and simple design it adjusted automatically to the width of your browser screen. Image sliders add life and interactivity to your web contents. But creating an image slider from scratch is not that easy. You need some good programming skills to create your own slider. If you are not the programmer or you just don’t want to re-invent the wheel, Responsive_DG_Slider is for you. Previously, I have already developed a very simple and useful slider i. e. jQuery – DG_Slider.
jquery-responsive-slider

Configuring Your Slider

Configuring the slider is very simple, you just need to place your images and call the initializer function and your slider is ready. Here’s how you can do this for full-screen.

The HTML

For develping a Full-Screen Background image slider you need to create the necessary HTML markups for your slider and then add references to necessary script files.

<div class="fluid_container">
        <div class="fluid_dg_wrap fluid_dg_emboss pattern_1 fluid_dg_white_skin" id="fluid_dg_wrap_4">
            <div data-thumb="slides/thumbs/1.jpg" data-src="slides/1-1280x720.jpg"></div>
            <div data-thumb="slides/thumbs/2.jpg" data-src="slides/2-1280x720.jpg"></div>
            <div data-thumb="slides/thumbs/3.jpg" data-src="slides/3-1280x720.jpg"></div>
            <div data-thumb="slides/thumbs/4.jpg" data-src="slides/4-1280x720.jpg"></div>
            <div data-thumb="slides/thumbs/5.jpg" data-src="slides/5-1280x720.jpg"></div>
            <div data-thumb="slides/thumbs/6.jpg" data-src="slides/6-1280x720.jpg"></div>
        </div>
</div>

The CSS

We have to link it’s default css file.

<link rel='stylesheet' id='fluid_dg-css'  href='css/fluid_dg.css' type='text/css' media='all'>

After attaching the default CSS, now we will customize it according to our requirement.

.fluid_container {
	bottom: 0; height: 100%; left: 0; position: fixed; right: 0; top: 0; z-index: 0;
}
#fluid_dg_wrap_4 {
	bottom: 0; height: 100%; left: 0;
	margin-bottom: 0 !important;
	position: fixed; right: 0; top: 0;
}
.fluid_dg_bar {
	z-index: 2;
}
.fluid_dg_prevThumbs, 
.fluid_dg_nextThumbs, 
.fluid_dg_prev, 
.fluid_dg_next, 
.fluid_dg_commands, 
.fluid_dg_thumbs_cont {
	background: #222;
	background: rgba(2, 2, 2, .7);
}
.fluid_dg_thumbs {
	margin-top: -100px; position: relative; z-index: 1;
}
.fluid_dg_thumbs_cont {
	border-radius: 0;
	-moz-border-radius: 0;
	-webkit-border-radius: 0;
}
.fluid_dg_overlayer {
	opacity: .1;
}

The jQuery

First, We have to add some jQuery library.

    <script type='text/javascript' src='http://code.jquery.com/jquery-1.6.2.min.js'></script>
    <script type='text/javascript' src='Scripts/jquery.mobile.customized.min.js'></script>
    <script type='text/javascript' src='Scripts/jquery.easing.1.3.js'></script> 
    <script type='text/javascript' src='Scripts/fluid_dg.min.js'></script>

After adding all these library we have to initiate the Responsive_DG_Slider. In this slider’s API we have several customization options. Here we are customizing some options according to this full-screen slider.

jQuery(document).ready(function(){
	jQuery(function(){			
		jQuery('#fluid_dg_wrap_4').fluid_dg({height: 'auto', loader: 'bar', pagination: false, thumbnails: true, hover: false, opacityOnGrid: false, imagePath: ''});
	}); 
})

Done!

That’s all, I hope you liked this article. Please feel free to comment and share your thoughts/ideas about the result.
view demo

Updated

APIs and other options of this wonderful plugin, please click here.

You may like:

Posted by: Dhiraj kumar

Snow-Fall Effect with JavaScript – Creating Merry Christmas Greetings

On the occasion of Christmas and winter Holidays, I thought to wish this festival by create a nice webpage greetings. So, today I had created this Christmas greeting card using snow-fall effect with help of CSS3 and JavaScript. I hope you all will enjoy this holiday and my web-card too :).

Today we will create a Christmas greeting card using CSS3 and jQuery. There are many things we can do with CSS3 and javascript. We’ll use snowfall.dg.js for creating these snow.

snowfall-effect-javascript-christmas-greetings

Features and Principle

Note: Snowfall Plugin is Less than 12Kb in size. There are many options for customize and use this plugin as per your requirement. Some features are:

  • No need to add any image for snow.
  • No need to add any JavaScript library.
  • You can use any html element in place of snow.
  • Change the Color of Snow by using hexadecimal value.
  • Also support in iPhone, iPad and Mobile devices.
  • Snow-fall movement with mouse/cursor.
  • Stick on bottom.
  • Snow melt effect.
  • Twinkle effect – you can use this also if you want star-fall 🙂
  • More options..

What this script does is adds snow-fall to the body. You can find more options in snowfall.dg.js.

The CSS

No special css required for snow fall effect. But in this greeting card, I have used css for background and my greeting message.

body{
         font-size:18px; 
         background:#badaf3 url(merry_chirstmas-wide.jpg) 100% 0 no-repeat; 
         background-size:cover; 
         font-family: 'IM Fell Double Pica', georgia, serif;
}
#welcome{
         font-size:2em; 
         width:40%; 
         margin:4%; 
         text-align:center; 
         background-color:#fff; 
         -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=70)";
         background:rgba(255,255,255,.75); 
         border-radius:10px; 
         box-shadow:4px 4px 10px 0 rgba(20,20,20,.6); 
         text-shadow: 2px 2px 3px #fff; 
         font-style:italic; 
         padding:1em; 
         color:#700; 
         color:rgba(120,0,20,.9)
}

The Html

<div id="welcome">May the miracle of Christmas fill your heart with 
warmth & love. 
Christmas is the time of giving and sharing.
It is the time of loving and forgiving. 
Hope you and your family have
wonderful Holiday... &... Merry Christmas to Everyone! </div>

Snowfall – The javascript

We have to add this snowfall.dg.js in body. I always prefer to use JavaScript files before close of body tag.

<script type="text/javascript" src="snowfall.dg.js"><script>

view demo

Updated!

I have updated this greetings with Jingle bells music and Html5 audio tags. now our Html is

<div id="welcome">May the miracle of Christmas fill your heart with 
warmth & love. 
Christmas is the time of giving and sharing.
It is the time of loving and forgiving. 
Hope you and your family have
wonderful Holiday... &... Merry Christmas to Everyone! </div>
 <audio autoplay="true" loop="true">
   <source src="jingle_bells_merry.ogg" type="audio/ogg">
   <source src="jingle_bells_merry.mp3" type="audio/mpeg">
Your browser does not support the audio element (HTML5). Please update your Browser.
 </audio>

Merry Christmas

I hope you like the result and don’t hesitate to share your thoughts about it. Thanks for reading!

Posted by: Dhiraj kumar

Cool Typography Effects With CSS3 and jQuery

Today we will create a set of nice typography effects for big headlines using CSS3 and jQuery. There are many things we can do with CSS3 animations and transitions and we’ll explore some of the possibilities.

Today we will create a set of nice typography effects for big headlines using CSS3 and jQuery. There are many things we can do with CSS3 animations and transitions and we’ll explore some of the possibilites.

We’ll be using jquery.DG_lettering.js in order to style single letters of the words we’ll be having in our big headlines.

typography-effects-with-css-jquery

THE HTML

The structure will simply be an h2 element with an anchor inside. We’ll wrap the headline in a container:

<div id="letter-container" class="letter-container">
    <h2><a href="#">Sun</a></h2>
</div>

Then we’ll call the jquery.DG_lettering.js plugin, so that every letter gets wrapped in a span.

This example looks crazy: we’ll create a text shadow that “elevates” the letters. We’ll also create a pseudo element which has a superhero as background.

THE CSS

.letter-container h2 a:before{
    content: '';
    position: absolute;
    z-index: 0;
    width: 525px;
    height: 616px;
    background: transparent url(superhero.png) no-repeat center center;
    background-size: 40%;
    top: 0px;
    left: 50%;
    margin-left: -277px;
    transition: all 0.3s ease-in-out;
}

On hover, we will animate the background size to make the superhero larger:

.letter-container h2 a:hover:before{
    background-size: 100%;
}

The span will have the text-shadow that “elevates” the letters and on hover, we will move the letter down by adding a padding and changing the shadow:

.letter-container h2 a span{
    color: #ff3de6;
    float:left;
    position: relative;
    z-index: 100;
    transition: all 0.3s ease-in-out;
    text-shadow:  
      0px -1px 3px #cb4aba, 
      0 4px 3px #934589, 
      2px 15px 5px rgba(0, 0, 0, 0.2), 
      1px 20px 10px rgba(0, 0, 0, 0.3);
}
.letter-container h2 a span:hover{
    color: #e929d0;
    padding-top: 10px;
    text-shadow:  
      0px -1px 3px #cb4aba, 
      0 4px 3px #934589, 
      1px 1px 10px rgba(0, 0, 0, 0.2);
}

And that’s it! I hope you enjoyed creating some crazy typography effects with CSS3 and jQuery!

view demo

That’s it!

I hope you enjoyed this article and if you have questions, comments, or suggestions, let me know! Thanks for reading.

Posted by: Dhiraj kumar

Random 3D Explosions, 3D clouds – Effects with CSS 3D and jQuery

Introduction

This tutorial will try to guide you through the steps to create a 3D-like, explosions in sky or billboard-based clouds. There are a few advanced topics, mainly how 3D transformations via CSS properties work. If you want to find more information, this is a nice place to begin.

If you’re in a hurry, just check the final result.

css-3d-explosive-clouds

The tutorial is divided into sections, each with a different step to understand and follow the process, with HTML, CSS and Javascript blocks. Each step is based on the previous one, and has a link to test the code. The code in the tutorial is a simplified version of the demos, but the main differences are documented on every section.

HTML

First, we need two div elements: viewport and world. All the rest of the elements will be dynamically created.

Viewport covers the whole screen and acts as the camera plane. Since in CSS 3D Transforms there is no camera per se, think of it as a static sheet of glass through which you see a world that changes orientation relative to you. We’ll position all our world objects (or scene) inside it, and that’s what will be transformed around.

World is a div that we are going to use to anchor all our 3D elements. Transforming (rotating, translating or scaling) world will transform all our elements. For brevity and from here on, I’m using non-prefixed CSS properties. Use the vendor prefix (-webkit, -moz, -o, -ms, etc.) where appropriate.

This is all the markup we’ll need:

<div id="viewport">
    <div id="world"></div>
</div>

CSS

These next are our two CSS definitions. It’s very important to center the div that contains our scene (world in our case) in the viewport, or the scene will be rendered with an offset! Remember that you are still rotating an element that is positioned inside the document, exactly like any other 2D element.

#viewport {
	-webkit-perspective: 1000; -moz-perspective: 1000; -o-perspective: 1000; 
	position: absolute; 
	left: 0; 
	top: 0; 
	right: 0; 
	bottom: 0; 
	overflow: hidden;
	background-image: linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -o-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -moz-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -webkit-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -ms-linear-gradient(bottom, rgb(69,132,180) 28%, rgb(31,71,120) 64%);
	background-image: -webkit-gradient(
			linear,
			left bottom,
			left top,
			color-stop(0.28, rgb(69,132,180)),
			color-stop(0.64, rgb(31,71,120))
	);
}

#world {
	position: absolute; 
	left: 50%; 
	top: 50%; 
	margin-left: -256px; 
	margin-top: -256px; 
	height: 512px; 
	width: 512px; 
	-webkit-transform-style: preserve-3d; 
	-moz-transform-style: preserve-3d; 
	-o-transform-style: preserve-3d; 
	pointer-events: none;
}

CSS For Adding Clouds Base

Now we start adding real 3D content. We add some new div which are positioned in the space, relatively to world. It’s esentially adding several absolute-positioned div as children of world, but using translate in 3 dimensions instead of left and top. They are centered in the middle of world by default. The width and height don’t really matter, since these new elements are containers for the actual cloud layers. For commodity, it’s better to center them (by setting margin-left and margin-top to negative half of width and height).

.cloudBase {
		position: absolute; 
		left: 256px; 
		top: 256px; 
		width: 20px; 
		height: 20px; 
		margin-left: -10px; 
		margin-top: -10px
	}

CSS for Clouds Layer

Now things start getting interesting. We add several absolute-positioned .cloudLayer div elements to each .cloudBase. These will hold our cloud textures.

.cloudLayer {
		position: absolute; 
		left: 50%; 
		top: 50%; 
		width: 256px; 
		height: 256px; 
		margin-left: -128px; 
		margin-top: -128px; 
		-webkit-transition: opacity .5s ease-out; 
		-moz-transition: opacity .5s ease-out; 
		-o-transition: opacity .5s ease-out;
	}

jQuery (JavaScript)

We add generate() and createCloud() functions to populate world. Note that random_{var} are not real variables but placeholder names for the real code, which should return a random number between the specified range.

var layers = [],
	objects = [],
	textures = [],

	world = document.getElementById( 'world' ),
	viewport = document.getElementById( 'viewport' ),

	d = 0,
	p = 400,
	worldXAngle = 0,
	worldYAngle = 0,
	computedWeights = [];

	viewport.style.webkitPerspective = p;
	viewport.style.MozPerspective = p;
	viewport.style.oPerspective = p;
	textures = [
		{ name: 'white cloud', 	file: 'cloud.png'	, opacity: 1, weight: 0 },
		{ name: 'dark cloud', 	file: 'darkCloud.png'	, opacity: 1, weight: 0 },
		{ name: 'smoke cloud', 	file: 'smoke.png'	, opacity: 1, weight: 0 },
		{ name: 'explosion', 	file: 'explosion.png'	, opacity: 1, weight: 0 },
		{ name: 'explosion 2', 	file: 'explosion2.png'	, opacity: 1, weight: 0 },
		{ name: 'box', 		file: 'box.png'		, opacity: 1, weight: 0 }
	];

	function setTextureUsage( id, mode ) {
		var modes = [ 'None', 'Few', 'Normal', 'Lot' ];
		var weights = { 'None': 0, 'Few': .3, 'Normal': .7, 'Lot': 1 };
		for( var j = 0; j < modes.length; j++ ) {
			var el = document.getElementById( 'btn' + modes[ j ] + id );
			el.className = el.className.replace( ' active', '' );
			if( modes[ j ] == mode ) {
				el.className += ' active';
				textures[ id ].weight = weights[ mode ];
			}
		}
	}
	setTextureUsage( 0, 'Few' );
	setTextureUsage( 1, 'Few' );
	setTextureUsage( 2, 'Normal' );
	setTextureUsage( 3, 'Lot' );
	setTextureUsage( 4, 'Lot' );

	generate();

	function createCloud() {

		var div = document.createElement( 'div'  );
		div.className = 'cloudBase';
		var x = 256 - ( Math.random() * 512 );
		var y = 256 - ( Math.random() * 512 );
		var z = 256 - ( Math.random() * 512 );
		var t = 'translateX( ' + x + 'px ) translateY( ' + y + 'px ) translateZ( ' + z + 'px )';
		div.style.webkitTransform = t;
		div.style.MozTransform = t;
		div.style.oTransform = t;
		world.appendChild( div );

		for( var j = 0; j < 5 + Math.round( Math.random() * 10 ); j++ ) {
			var cloud = document.createElement( 'img' );
			cloud.style.opacity = 0;
			var r = Math.random();
			var src = 'troll.png';
			for( var k = 0; k < computedWeights.length; k++ ) { 
				if( r >= computedWeights[ k ].min && r <= computedWeights[ k ].max ) { 					
( function( img ) { img.addEventListener( 'load', function() {
 						img.style.opacity = .8;
					} ) } )( cloud );
 					src = computedWeights[ k ].src; 
}} 
cloud.setAttribute( 'src', src ); 
cloud.className = 'cloudLayer'; 		 			
var x = 256 - ( Math.random() * 512 ); 
var y = 256 - ( Math.random() * 512 ); 
var z = 100 - ( Math.random() * 200 ); 
var a = Math.random() * 360; 
var s = .25 + Math.random(); 
x *= .2; y *= .2; 
cloud.data = {x: x, y: y, z: z, a: a, s: s, speed: .1 * Math.random()}; 
var t = 'translateX( ' + x + 'px ) translateY( ' + y + 'px ) translateZ( ' + z + 'px ) rotateZ( ' + a + 'deg ) scale( ' + s + ' )'; 
cloud.style.webkitTransform = t; 
cloud.style.MozTransform = t; 			
cloud.style.oTransform = t; 			
div.appendChild( cloud ); 			
layers.push( cloud ); 		} 		 		
return div; 	 	
function generate() { 		
objects = []; 		
if ( world.hasChildNodes() ) { 			
while ( world.childNodes.length >= 1 ) {
				world.removeChild( world.firstChild );       
			} 
		}
		computedWeights = [];
		var total = 0;
		for( var j = 0; j < textures.length; j++ ) { 			
if( textures[ j ].weight > 0 ) {
				total += textures[ j ].weight;
			}
		}
		var accum = 0;
		for( var j = 0; j < textures.length; j++ ) { 			
if( textures[ j ].weight > 0 ) {
				var w = textures[ j ].weight / total;
				computedWeights.push( {
					src: textures[ j ].file,
					min: accum,
					max: accum + w
				} );
				accum += w;
			}
		}
		for( var j = 0; j < 5; j++ ) {
			objects.push( createCloud() );
		}
	}

Result

For the final effect, we fill cloudLayer div for an img with a cloud texture. The textures should be PNG with alpha channel to get the effect right.

css-3d-explosive-clouds

Conclusion

Of course, you can use any texture or set of textures you want: smoke puffs, plasma clouds, green leaves, flying toasters… Just change the background-image that a specific kind of cloud layer uses. Mixing different textures in different proportions gives interesting results.

Adding elements in random order is fine, but you can also create ordered structures, like trees, duck-shaped clouds or complex explosions. Try following a 3D curve and create solid trails of clouds. Create a multiplayer game to guess the shape of a 3D cloud. The possibilities are endless!

I hope it’s been an interesting tutorial and not too hard to follow.

view demo

I hope you like the result and don’t hesitate to share your thoughts about it. Thanks for reading!

Posted by: Dhiraj kumar

Hot Tea / Coffee with Animated Smoke Effect – jQuery & CSS

This effect has been created with some cool jQuery animation effect. For Smoke effect I have used a png transparent image. I have already updated this for IE too. As we already know transparency of png creates some bad side-effects on IE (png transparency bugs in IE). You can check the demo code and see how it’s done. Basically, the Javascript function creates some div with smoke background in random positions.  so, the effect looks more random even though it’s totally deterministic. Each smoke moves in the Y axis with a linear function and fade with a cosine function. Pretty simple effect, but effective.

css-jquery-smoke-animation-effect-of-coffee-tea

The CSS

#viewport {
position: relative;
width: 800px;
height: 600px;
overflow: hidden;
background:url('images/milk_tea.jpg') 0 0 no-repeat
}
#viewport .smoke {
position: absolute;
width: 250px;
height: 250px;
background:url('images/smoke-texture.png') no-repeat;
bottom: 150px;
margin-left:0px
}

The jQuery

Now, We are including jquery library and the easing plugin for creating this affect realistic.

<script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script src="http://demo.web3designs.com/jquery-easing.min.js"></script>
<script type="text/javascript">
$(function () {
    if (!$.browser.msie) {
        var a = 0;
        for (; a < 15; a += 1) {
            setTimeout(function b() {
                var a = Math.random() * 1e3 + 5e3,
                    c = $("
", {
                        "class": "smoke",
                        css: {
                            opacity: 0,
                            left: Math.random() * 200 + 80
                        }
                    });
                $(c).appendTo("#viewport");
                $.when($(c).animate({
                    opacity: 1
                }, {
                    duration: a / 4,
                    easing: "linear",
                    queue: false,
                    complete: function () {
                        $(c).animate({
                            opacity: 0
                        }, {
                            duration: a / 3,
                            easing: "linear",
                            queue: false
                        })
                    }
                }), $(c).animate({
                    bottom: $("#viewport").height()
                }, {
                    duration: a,
                    easing: "linear",
                    queue: false
                })).then(function () {
                    $(c).remove();
                    b()
                })
            }, Math.random() * 3e3)
        }
    } else {
        "use strict";
        var a = 0;
        for (; a < 15; a += 1) {
            setTimeout(function b() {
                var a = Math.random() * 1e3 + 5e3,
                    c = $("
", {
                        "class": "smoke",
                        css: {
                            left: Math.random() * 200 + 80
                        }
                    });
                $(c).appendTo("#viewport");
                $.when($(c).animate({}, {
                    duration: a / 4,
                    easing: "linear",
                    queue: false,
                    complete: function () {
                        $(c).animate({}, {
                            duration: a / 3,
                            easing: "linear",
                            queue: false
                        })
                    }
                }), $(c).animate({
                    bottom: $("#viewport").height()
                }, {
                    duration: a,
                    easing: "linear",
                    queue: false
                })).then(function () {
                    $(c).remove();
                    b()
                })
            }, Math.random() * 3e3)
        }
    }
}())</script>

view demo

Update:

I’ve done some changes in my jquery script and fix IE png transparency bug.

Thanks for reading and looking forward to read your thoughts!

Posted by: Dhiraj kumar

Animated Notification bubble icon with CSS3 keyframe animation

The other day, while working on a web project, I had to emphasize somehow a dynamic notification bubble. Basically, every time the notification value changes, a visual effect was needed in order to get user’s attention. So I made that using CSS3 keyframe animation.

notification-bubble-animation

The HTML

For this example, we’ll borrow the markup structure and look from my CSS3 dropdown menu.

<ul>
    <li><a href="">Dashboard</a></li>
    <li><a href="">Friends</a></li>
    <li>
    	<a href="">Message
    		<span>9</span>
    	</a>
    </li>
    <li><a href="">Games</a></li>
    <li><a href="">Settings</a></li>
</ul>

The focus will be on the <span>, which is the notification bubble that will be animated.

The CSS

The .animating class represents an CSS3 animation that uses a bezier curve.

.animating{
	animation: animate 1s cubic-bezier(0,1,1,0);			
}

@keyframes animate{
	from {
	   transform: scale(1);
	}
	to {
	   transform: scale(1.7);
	}
}

The jQuery

It’s not as easy as you might think to restart an animation and Chris Coyier wrote a good article about it.

The method I chose for this example involves using JavaScript’s setTimeout() method. So, every time the notification value changes, the .animating class is removed after a second (exactly how long the proper animation lasts).

In production, you will not need the counterValue variable. This is used just for our working example in order to be able to increment and decrement the notification value.

var counterValue = parseInt($('.bubble').html()); // Get the current bubble value

function removeAnimation(){
	setTimeout(function() {
		$('.bubble').removeClass('animating')
	}, 1000);			
}

$('#decrease').on('click',function(){
	counterValue--; // decrement
	$('.bubble').html(counterValue).addClass('animating'); // animate it
	removeAnimation(); // remove CSS animating class
})

$('#increase').on('click',function(){
	counterValue++; // increment
	$('.bubble').html(counterValue).addClass('animating'); // animate it
        removeAnimation(); // remove CSS animating class

view demo

Simple, but effective

I think this is a simple and practical example on how to use a CSS3 animation to enhance user experience. Further, you can experiment with the bezier curve values and come up with some other cool effects.

Thanks for reading and looking forward to read your thoughts!

Posted by: Dhiraj kumar

jQuery Plugin for Cartoon-like Background Image Sprite Animation – AniDG – (alernative to animated Gif)

What is AniDg?

AniDg is a simple plugin for jQuery which allows you animate background images. The plugin is basically an alternative to the animated GIF but with several benefits. At first, it’s always better to use an animated GIF as this format is supported by all browsers without any JavaScript code or additional markup, but the “dark side” of it is that an animated GIF allows only 256 colors and you cannot control animation in any way. The AniDg loads a long vertical image and changes its background position with the speed you setup, giving you more control of the animation. For Better quality you can call PNG, JPG, GIF images in background image sprite as per your requirements.

Demo

jQuery Plugin AniDG Background image animation

Features

  1. Light-weight script (Only 1Kb :))
  2. Easy to integrate
  3. Fully customizable via CSS
  4. Works with all modern browsers 🙂

How to Use

METHOD #1: EASY

Simply place the following code anywhere inside thetag of your webpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://demo.web3designs.com/jquery-ani.dg.min.js"></script>

METHOD #2: ADVANCED

STEP ONE: Download AniDg.zip or http://demo.web3designs.com/AniDg.zip. The package already contains all files used in this demo.

STEP TWO: Unzip and place the file jquery-ani.dg.min.js in the same location as the webpage that is displaying the animation. (Make sure paths to files are correct.)

STEP THREE: include the following code in the <head>…</head> section of your webpage:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="jquery-ani.dg.min.js"></script>

3.) Add a style containing the url to your background with animation (this may be added to a separate CSS document or inside the <head>…</head> tag):

<style type="text/css">
#animation-1 {
background: url(images/sample-animation.gif) no-repeat left top;
}
</style>

4.) Add an empty DIV which will display animation in your document:

<div id="animation-1"></div>

5.) Add the following code to your <head>…</head> tag to initialize AniDg and start the animation.

<script type="text/javascript">
$(document).ready(function(){
$('#animation-1').anidg({ frameWidth: 100, frameHeight: 100, speed: 100, totalFrames: 19 });
$('#animation-1').anidg.play();
});
</script>

That’s it 😉 Click the Demo button to see it in action.

Public Functions

anidg.play()
Start playing animation.

anidg.pause()
Pause animation.

anidg.stop()
Stop animation.

Parameters

The table below contains a list of parameters accepted by the .anidg() function.

Parameters Description
frameWidth Width of a single frame.
frameHeight Height of a single frame.
speed Animation speed.
totalFrames Total frames in the animation.
loop Loop an animation or not. By default, value is true.

Posted by: Dhiraj kumar