Sunday, October 9, 2011

Javascript Array prototype and for-in

If you are developing a 3rd party application, a jQuery plugin or something similar, this will be specially useful for you.

I'm sure you've heard about it but you can extend the Javascript's core objects with the help of the prototype property. So, in this case let's see what happens if we combine Array.prototype with a for-in loop.

// let's create a simple array
var testArr = new Array(1, 2, 3);

// print it out to the console
for( var i in testArr ) {
 console.log(i+": "+testArr[i]);
}
// output: 
// 1
// 2
// 3

// extend the array object
Array.prototype.myMethod = function (arr) {
 // Do something here..
}

// loop the array again
for( var i in testArr ) {
 console.log(i+": "+testArr[i]);
}
// output: 
// 1
// 2
// 3 
// myMethod: function (arr) { }


As you can see, the second time in the loop the custom methos is also listed az an array item. This can be source of unknown bugs and I have spent a lot of time to figure this little trick out.

So, what are the solutions?
Use the Array object's "hasOwnProperty" property:
for( var i in arr) {
      if( !arr.hasOwnProperty( i ) ) continue;
      // stuff to do..
}

Or if you have jQuery loaded, use the .each method.
jQuery.each(testArr, function (key, value) {
 console.log(key+": "+value);
});


This possible bug source is kind of sneaky, yet the solution is simple :)

HowTo: Canvas colorful bouncing circle animation with JavaScript

Introduction


I've really really waited for the moment when I can start developing canvas animations. In this post I'm going to present you what I've coded and tell you a few words about its concept.

But, check out the Demo first.

So, as you've seen, the result is a canvas with bouncing and colorful circles. They are random positioned with random colors, random directions and random sizes. But, what is a canvas? Canvas is a part of Html5 specification. You can use it to draw graphics and animations with the help of JavaScript.

<canvas width="400" height="300"></canvas>

I won't go into basics of canvas element. If you are interested about it, please check out Mozilla Developer Network's Canvas Tutorial.

Animation basics

Frames. All we need is them. A frame is a 'screenshot' of the current state of a scene. A scene contains the objects and pretty much everything we want to draw to the audience. We create an animation from frames by drawing at least 24 to the screen in every second. This is the minimum amount to deceive the eye to see motion on the screen. Of course, the more frames we draw in one second, the smoother the animation gets. From frame to frame we must update and redraw all of the objects. Everytime we create an animation the following things happen:
  1. Initialization
  2. Updating scene
  3. Drawing scene
  4. While it must be drawn, jump back to the 2. point else 5.
  5. End of animation

The 2., 3. and 4. point together forms the main loop. This is where all of the scene objects' state, position, color etc. gets updated and gets drawn. If you wish to put user input to the animation (etc, mouse movement) there would be a new item in the list for input handling.

Skeleton of my animation object

var animation = function() {
 /* List of objects to draw (the particles) */
 var list = [];

 /* Frame per seconds */
 var fps = 24;

 /* Object constructor */
 var particle = function() {};
 
 /* Initialization */
 this.init = function(v) {};

 /* Updating objects state, position, etc.. */
 var update = function() {};

 /* Drawing the objects */
 var draw = function() {};

 /* Calling update() and draw() */
 var loop = function() {};

 /* Setting main loop */
 this.play = function() {};
}

The above source snippet is the skeleton of my animation object.

Initialization

Bouncing circles on the screen represented as a particle object. The animation itself has a variable called list. Every item of it will be a new particle object. Calling the init() function with a number parameter will add as much particles to the animation as much we want.

Particles

Particles object looks like this:
/* Particle object */
  var particle = function() {
    /* Coordinates */
    this.x = 0;
    this.y = 0;

    /* The radius of circles */
    this.radius = 5;

    this.speed_x = 1;
    this.speed_y = 1;

    /* Direction */
    this.dx = 0;
    this.dy = 0;

    this.color = {
      fill : '#000',
      stroke : '#000'
    }

    /* Boundaries (canvas width and height) */
    this.bounds = {
      x0 : 0,
      x1 : 600,
      y0 : 0,
      y1 : 400
    }

    /* Private function for random color but I think you've already guessed that. */
    var random_color = function(){}

    /* Function to initialise variables */
    this.init = function() {}

    /* Updater function, called at every frame. It updates positions and check boundaries. */
    this.update = function() {}
  }

To represent a circle on the screen I stored information about it such as its x and y coordinate, its x and y speed, its direction, its colors and its boundaries because I don't want it to go away from the screen leaving a blank white field to the user. Init function sets variables to random values. The update function is used to update the circles properties in every loop. It will be called by the loop's update function.

Updating and drawing

I've defined a loop function. It simply calls the update() and draw() once. To create the animation by calling the loop function multiple times in every second I have to use the setInterval() function.

/* To start animation */
this.play = function() {

 /* Animloop */                        
 setInterval(loop, 1000/fps);          
      
};

The first parameter must be a function what will be called, and the second parameter must be a number representing a ms value. Let's say I want it to call 24 times a second, then I must divide 1000 by the fps rate (24 now) to get the desired ms values.


var ANIM = new animation();
ANIM.init(25);
ANIM.play();

Final words

This is a basic animation concept. I hope you found it useful. Play with it online on this link at JsFiddle.net. If you would like to say anything or noticed something, please leave a comment.

jQuery: Checkbox howto

Once I've run into a project with a complicated form where some ajax didn't work. After digging into the code I've sadly seen a mistake that caused the functionality loss.

As you know, checkbox state can be determine at least two ways:
/* checkbox */
var chk1 = $('#chk1');   
               
chk1.attr('checked');
/* or */
chk1.is(':checked');

The previous programmer used the attr() function, however he forgot (or did not know...?) the difference between the two. While attr() function returns the attribute of the checkbox (undefined if not checked, 'checked' if checked), the second is() function returns boolean true or false. He sent the return value of attr() call as a string to a php script, but he expected 'true' or 'false', but he got 'checked' or 'undefined'.

/* checkbox */
var chk1 = $('#chk1');
chk1.attr('checked', true);

// returns 'checked' but it evaluates to boolean true in javascript
if(chk1.attr('checked')) {
    
}

// returns boolean true                
if(chk1.is(':checked')){
    
} 

Another note, to check a checkbox you can use:
chk1.attr('checked',true);

To uncheck a checkbox, you can do:
chk1.attr('checked', false);
/* or */
chk1.removeAttr('checked');

So the conclusion is to be careful out there and always know what a function will return!

Friday, October 7, 2011

jQuery speed test - sibling selector

I'll continue the previous post with a similar one. But this time I tested the sibling selector of jQuery. And as it turned out it is quite interesting but I don't want to kill the joke too early, so let's see that pic:


Well, IE is...slow, so to see things clearer I have removed it from the graph:


Obviously the fastest solution is: jQuery("h1 + h2")

BUT... there are some really interesting things going there. How can it be, that jQuery("h1").siblings("h2") is sooo much slower, than this:

jQuery("h2").filter(function () {
    return jQuery(this).prev()[0].tagName == "H1";
});


If anybody knows the answer, please share it with us!

jQuery speed test - child selector

Selecting child elements with jQuery is not a challange. However selecting it the fastest way is. I did a simple jQuery selector speed test with the latest versions of Firefox, Chrome, Opera and Internet Exporer. The values you see here are in milliseconds per 1000 cycle.

Here is what I got:


Based on the previous chart it seems... well, quite obvious that IE is the slowest and Chrome is the fastest... but returning to the topic... :)

Here are the comparisons of the fastest ways of getting the children elements (the datas from IE are excluded from the test now due to the large difference):

For all child elements the best way is:
jQuery("li > *"). It's:
  • ~29.4% faster than jQuery("li").children()
  • ~86.1% faster than jQuery("> *", li)
  • ~140% slower than li.children()

And for only link elements the best method is:
jQuery("li > a"). It's:
  • ~65.2% faster than jQuery("li").children("a")
  • ~87.5% faster than jQuery("> a", li)
  • ~47.3% faster than li.children("a")

The other thing to observe is that the loops are much faster if you store the base jQuery wrapper object in a variable.

Saturday, August 20, 2011

Javascript - pausing script flow ( sleep )

Sometimes it happens, that I need to PAUSE the flow of my script. And I mean pause, with capital letters, because these times a simple setTimeout would not help.

There is a very nice, browser independent method to do this:

1. Create a synchronous AJAX call
2. On the server side call the "sleep( [sec] )" function

To speak in code, this is the javascript (jQuery) part of it:

function pause(millisec) {
	jQuery.ajax({
		type: "GET",
		url: "index.php",
		data: {
			task: 'pause',
			pauseMillisec: millisec
		},
		async: false
	});
}


And this is the PHP part:

<?php 
if( $_GET["task"] == "pause" ) {
	sleep( $_GET["pauseMillisec"]/1000 );
} 
?>

That's all folks.. isn't it easy? :)

Feel free to share your thoughts with me.

Sunday, March 20, 2011

jQuery broken picture fixer

Description: fixes and handles pictures which are not found.

During website development there are always pictures which can not be found. In Firefox these pictures are automatically hidden, but for example in Internet Explorer they are marked with a little image with a red “X” in it (which is quite ugly by the way). It's better to show your own “nopic” picture, which suits to your own design and taste. Furthermore, when you have to alter your layout if a picture is not found, you can handle it client side with this jQuery plugin.

What is this good for? ... Well, you can:
  • mark the broken images on your site the way you like it
  • replace automatically these images to a default “nopic” picture
  • define a custom callback function, if a picture is not found
  • solve the tasks above with a jQuery plugin with a very small footprint

“Nice...this is very useful! But how can I use it?”

It's pretty simple.

Basic usage: Default “nopic” image is “images/nopic.jpg”
1
jQuery(".picture").picfix();

Default image configuration: With the “altImg” parameter.
1
2
3
jQuery(".picture").picfix({
    altImg: "images/mynopicture.jpg"
});

Error handling configuration: With the “onerror” parameter.
1
2
3
4
5
jQuery(".picture").picfix({
    onerror: function () {
        // do something...
    }
});

Files:
  • jquery.picfix.min.js (~0.53kb)
  • jquery.picfix.compressed.js (~0.58kb)
  • jquery.picfix.js (~0.79kb)
  • usage.js

Download:

Feel free to write me a comment, and if you like this little plugin please contribute my efforts.