Archive for the ‘Javascript’ Category

Javascript version compare function

May 4th, 2013

Here’s quick javascript function for comparing versions. It works with any type of version strings, but it does not check for suffixes like ‘RC’, ‘alpha’, ‘stable’, etc. This was written in less than 10 minutes, so let me know if you find any bugs. Suggestions are welcomed anytime!

function versionCompare(a, b) {
	var A = a.split('.'), B = b.split('.'), ret = 0, base, sig, x, y;
	for(var i = 0, n = Math.max(A.length, B.length); i < n; i++) {
		x = 'undefined' == typeof A[i] ? 0 : parseInt(A[i]);
		y = 'undefined' == typeof B[i] ? 0 : parseInt(B[i]);
		base = Math.pow(10, n - i - 1);
		sig = 0;
		if( x < y ) { sig = -1; }
		else if( x > y ) { sig = 1; }
		ret += sig * base;

	return ret == 0 ? 0 : ret / Math.abs(ret);


Prototype 1.6, Event.stop and IE9 – Quick patch

November 30th, 2011

For those of you using Prototype 1.6 (or Magento prior 1.6), you might wonder why event.stop() or Event.stop(event) doesn’t work in Internet Explorer 9. Here’s a quick explanation:

IE 9 makes major changes to the event system. We had to rewrite the
event code in 1.7 to support it. You can either (a) upgrade to 1.7;
(b) force your site into compatibility mode [1].

So it’s been fixed in 1.7, but what if I can’t upgrade to 1.7 and don’t want to render my website in compatibility mode? Well, after a couple of hours trying to sort this out, here’s quick (and dirty) patch for Prototype Prototype Event.stop IE9 fix (1296 downloads)

Also, for further reading, here are two external links that you might find useful for this issue.

Note/Disclaimer: This has only been tested on Prototype Use it at your own risk.

Javascript , ,

Strange Prototype’s Class.create behavior

November 1st, 2011

A few more months and it would’ve been a year since the last post. Worry not, this blog hasn’t died – and just to make sure I don’t forget what I want to write, I’ve already prepare a few articles. So stay tuned!

But enough with the intro and let’s see what this article is about: Prototype (, not really my favorite javascript framework, but since Magento relies on it, I need to be able to use it and write proper code (I don’t believe in mixing frameworks either).

The scenario is rather simple – create a “class” called Stuff and then instantiate two objects of that class.

var Stuff = Class.create({
	data: {},
	x: null,
	y: [],
	initialize: function() {}

var a = new Stuff();
var b = new Stuff();

So far so good, because the code does nothing, but let’s add the following: = 1;
a.x = 5;

What would you expect b to contain? From my (lack of) knowledge, I would say is an empty object, b.x is null and b.y is an empty list/array. At least that’s how it goes in other programming languages, such as PHP. Well, this doesn’t happen here. If you do console.log(b) you’ll get:

data	Object { x=1}
x	null
y	[3]

In other words, object and array attributes have the same reference, or point to the same object. I would’ve said that the variables a and b are pointing to the same object, if a.x was the same as b.x, but b.x is still null, while a.x is 5.

Bug, feature or normal behavior, this can still be very annoying – I spent about an hour trying to figure out why two objects of the same “class” had the same settings when they were clearly configured differently. Hope this comes in handy at some point.

Tested on prototype v1.6.0.3 & v1.6.1.

Javascript ,

The eternal question: jQuery or MooTools?

June 23rd, 2009

It’s been a while since my last post and even more since I first thought of writing a comparison post between MooTools, Prototype & jQuery. At that time (almost a year ago), I was a huge MooTools fan. Anyone who asked me “Hey I’m starting a new project, what javascript library should I use?” got the following answer: “MooTools, of course”. Nowadays, things have changed a bit and so has my vision on js frameworks.

Although my first intention was to compare Prototype, jQuery & MooTools, I’m going to only mention the last two in this post. Not that Prototype wouldn’t be a good choice, but because I have much more experience with the other two – and also because I’m not a big “fan” of Prototype. Anyway, besides these libraries, there are at least a dozen other full javascript frameworks that you could use, so in case this is your first time you hear of such things (hmm, I doubt it though), you should check out a few of them – Ext JS, YUI, dojo, MochiKit are some of the ones I checked, heard or used.

Back to our js “battle” – I believe I’m not the only one who had to decide which one to use. So, what did I choose? Both! Not in the same project, of course, but some of my projects use jQuery, some others are based on Moo Technology. You’ll probably say this is confusing and not helping you decide which one to use. First of all, I suggest you read this great article on jQuery vs MooTools – it was a great inspirational source for me and it also contains most of the language differences and basic approach. Then, let’s try and emphasis some of the key parts of using either of these two – I’m not going into code elements, you can check the manuals for that.


– very simple to use, so if you’re a designer or don’t have enough experience in programming (or OOP), stick to jQuery

– only one method to access dom elements – $() or jQuery() – this is great because it removes a lot of extra code, so instead of writing something like $$(selectors).each(function(el) {}) (mootools style) you can just write $(selectors).do()

– cool effects are very simple to use and can be applied really quick


– programatic approach, so if you’re a developer or an ex-programmer (and like OOP), this is for you

– two main methods for accessing dom elements – $() and $$() – again, the code is much more simple to understand when using $$(‘#id a.class’).each(), instead of the same $(‘#id a.class’) method as jQuery does. That’s why jQuery is simple, MooTools is “correct”

– the effects part of the library is very complex and allows a lot of chaining, grouping and transition effects. again, the only problem is that it takes a bit longer to write moo-code, than j-code.

Final Thoughts

I believe it’s clear enough what the main difference between jQuery and MooTools is: it’s HOW you write javascript code. No one can really tell jQuery is best, or MooTools rules – both of them are great libraries and both of them can come in handy if you know when to use them. From my own experience, I’d say if you have a small project, more design than development, use jQuery. If you have a more complex project, that involves more javascript code, maybe reusable elements, design patterns, classes, etc – use MooTools.

I remember that I didn’t like jQuery when I first got in touch with Moo, because it was very slow. I believe it sill is slower than Moo, but the difference is not that significant on small projects.

I think it’s best to know at least one js framework and stick to that, if it makes you more productive. But I also believe it’s only to your advantage to understand how others work.



Aaron Newton of Clientcide, the author of “jQuery vs MooTools”, added a disclaimer in his post, so I think it wouldn’t hurt to add one myself, otherwise I might get assaulted by un-happy prototype, extjs, dojo or yui developers 🙂 I’m currently using both MooTools and jQuery, and sometimes writing a few lines of code on Prototype. I don’t intend to promote either of these frameworks, it’s really up to you which one to choose. You could even write your own!

I’d be really glad to hear some of your thoughts on javascript libraries – which ones are you using and why, why you think a is better than b, etc.



Javascript , ,

Custom animation using jCarousel and jQuery

May 12th, 2009

Yet another javascript demo, this time using jQuery. For those of you who haven’t worked or heard of jQuery here’s a quick explanation taken from their website: jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.. So, first thing you need to do is go to and download the latest version if the library.

Next thing that you need is the jCarousel plugin, written by Jan Sorgalla – visit for more details.

Dont want to read everything? You can view the online demo or jCarousel Animation (2123 downloads)

Now you’re able to add carousel effects to both vertical lists and horizontal lists. I guess 90% of the time, jCarousel is flexible enough and will let you customize a lot of things from styles to behavior. However, today I wanted to add an effect to a list and I couldn’t make the plugin work as needed. Maybe I missed something, but anyway, here’s an example on how to change the default animations for jCarousel.

First, here’s the effect I wanted: on a horizontal carousel, elements auto scroll to the right until they reach the end, then change scroll to the left until they reach the start element. Let’s call this a variant of the circular wrap that can be defined with jCarousel.

Let’s setup the carousel – include style sheets and javascripts:

<link type="text/css" rel="stylesheet" href="res/jcarousel/jquery.jcarousel.css" media="screen" />
<link type="text/css" rel="stylesheet" href="res/jcarousel/skins/ie7/skin.css" media="screen" />

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="res/jcarousel/jquery.jcarousel.pack.js"></script>
<script type="text/javascript" src="js/pcarousel.js"></script>

then create the carousel markup:

<div class="pCarouselWrapper">
<div class="controls">
	<a href="#" class="pCarouselPrev">&laquo; prev</a>
	<a href="#" class="pCarouselStop">stop animation</a>
	<a href="#" class="pCarouselStart">start animation</a>
	<a href="#" class="pCarouselNext">next &raquo;</a>
<ul id="pCarousel" class="jcarousel-skin-ie7">
  <li>item data 1</li>
  <li>item data 2</li>
  <li>item data 3</li>
  <li>item data n</li>

I’ve added my own controls for prev() and next(), as well as a way to stop & start the animation. Now let’s configure the carousel:

jQuery(document).ready(function() {
    wrap: 'left',
    scroll: 1,
    visible: 3,
    initCallback: pCarousel.init,
    easing: 'linear',
    animation: pCarousel.animationSpeed,
    buttonPrevHTML: null,
    buttonNextHTML: null

Some quick comments, on the outcomes – shows 3 elements at once, scrolls only one each time, the movement effect is using linear easing (check out jQuery manual for more info on this) and default jCarousel control buttons are disabled. Everything is initialized via the pCarousel.init callback.

The effect is done by the pCarousel object:

var pCarousel = {
	animationId: null,
	animationDir: 'right',
	//time in miliseconds to wait before scrolling
	animationTimeout: 3000,
	//time in miliseconds for the scrolling transition
	animationSpeed: 250,
	init: function(carousel) {
		// Disable autoscrolling if the user clicks the prev or next button.
		carousel.clip.hover(function() { pCarousel.halt() }, function() { pCarousel.animate(carousel); });
		jQuery('a.pCarouselNext').bind('click', function() {
			return false;
		jQuery('a.pCarouselPrev').bind('click', function() {
			return false;
		jQuery('a.pCarouselStop').bind('click', function() {
			return false;
		jQuery('a.pCarouselStart').bind('click', function() {
			if( pCarousel.animationId ) { //already running
				pCarousel.animationDir = 'right';

			return false;
	animate: function(carousel) {
		pCarousel.animationId = setInterval( function() {
			if( carousel.last == carousel.options.size ) { pCarousel.animationDir = 'left'; }
			else if( carousel.first == 1 ) { pCarousel.animationDir = 'right'; }
			if( pCarousel.animationDir == 'right' ) {; }
			else { carousel.prev(); }
		}, pCarousel.animationTimeout );
	halt: function() {
		if( pCarousel.animationId ) {

Again, a few explanations – there are three methods, animate(), halt() and init(). Inside init(), we’re adding listeners on DOM elements and also a pseudo-listener (via the carousel object) that freezes animation while hovering the mouse over a list item.

The halt() method simply stops the current animation, by clearing the interval. Once again setInterval comes to the rescue!

The entire animation is handled by a setInterval() call, running the animation algorithm at specific intervals – the time that you want to keep the information on the screen (in this case, it’s 3 seconds). Then, the trick is to set a scrolling direction and change it each time the carousel reaches an end. By looking at the direction, you can either call next() or prev().

Nothing fancy, nothing new, but I think it’s a nice and useful animation.

Demo | jCarousel Animation (2123 downloads)

Javascript , ,

Create a gallery with fade-in effects using Mootools

March 21st, 2009

I was working on a photo gallery a couple of days ago and I thought I’d write a tutorial on adding neat effects on a gallery of items (usually photos).

Demo | Mootools Gallery (846 downloads)

The problem

I was showing 12 photos on a page and I didn’t like how it loaded – it simply looked too static. So I though of adding a nice fade in effect to each item. This could be even more useful when loading the photos via an AJAX request, which I intend to add to that gallery at a later time. First, let’s take a look at the gallery HTML:

<ul class="gallery">
	<li class="clear">
		<a href="#"><img alt="img_01" src="img/01.jpg"/></a>
		<h2>Image #1</h2>
		<a href="#"><img alt="img_02" src="img/02.jpg"/></a>
		<h2>Image #2</h2>


		<a href="#"><img alt="img_12" src="img/12.jpg"/></a>
		<h2>Image #12</h2>

I’m gonna add some basic CSS on this list, just to make it look like a grid, rather than a list – of course you can apply any styling on it.

.gallery {width: 540px; margin: 0 auto;}
.gallery li {opacity: 0; filter: alpha(opacity = 0); float: left; width: 100px; padding: 5px 10px 15px;}
.gallery li.clear {clear: left;}
.gallery li img {border: 1px solid #ccc; width: 100px;}

You can’t tell from the missing li elements, but I’m clearing each 4th element to create a 4×3 grid. Ok – so far the grid is in place, but we need the animation part – we could use any javascrpit framework, but for this project I had to use Mootools – for those of you that haven’t seen it and don’t what it is about, here’s a quick overview from their site: MooTools is a compact, modular, Object-Oriented JavaScript framework designed for the intermediate to advanced JavaScript developer.

The solution

First, we need to fetch all li elements:

var li = $$(' li');

then apply the animation effect:

li.each(function(e) {
e.set('tween', {duration: 500, transition: 'back:in'}).tween('opacity', 0, 1);

A few comments on this last piece of code:

  • e.sets(…) – set the duration to 500 and transition to “backIn” to all tweens
  • e.tween(‘opacity’, 0, 1) – animate (or tween) opacity from 0 to 1, using the options defined above

If you run this code you can clearly see that it doesn’t exactly produce the desired effect – all photos fade-in at once, because of the way the code is executed. The trick is to add an incremented timeout to each element:

var i = 0; //the current timeout
li.each(function(e) {
  i += 100; //adding the increment
  setTimeout( function() {
    e.set('tween', {duration: 500, transition: 'back:in'}).tween('opacity', 0, 1);
  }, i);

And that’s all! We now have a nice item-by-item fade-in effect. It’s worth mentioning that this effect can be changed by tweaking the three variables: the delay for each item, the speed of the effect and the tween effect. On the demo page I’ve made it possible to change the delay & speed, so you can make an idea of how they affect the general effect. The third parameter can be changed using any mootools transition (

Demo | Mootools Gallery (846 downloads)

Javascript , ,