Multiple Upload Using Single Upload File With jQuery

This is a trick to perform multiple upload using a single upload bar instead of multiple upload bars created by stickman. If you are looking for multiple upload using iframe or asynchronous method, you can visit this simplest way tutorial that explains how iframe method can be done and whether ajax method is available. I first came across stickman article was when i was doing research for multiple upload without having the file uploaded into the server. His idea was brilliant. However, i hardly have the need for such function until recently when my project submit form required multiple upload using a single upload bar again. Stickman method was pure JavaScript which is great and efficient but i needed something from jQuery. Here, i will try to simplify his method into jQuery form.

Concept of Single Multiple Upload File

In order to achieve single multiple upload file, we will have to understand that multiple upload is still possible even without asynchronous upload, that is, we will need multiple upload bar displaying on the screen and having user to click on each upload bar to upload multiple item at once. In stickman concept, its almost the same. The only differences is that he uses one upload bar and insert a new one on top of the existing upload bar AFTER a user has finished selected the item to be uploaded. Therefore it seems like there is only one upload bar. (the process is too fast for our eyes to follow. Thus, we all get trick when this happen) But in reality, all these upload bars were only hidden from user but not from codes. Once, the submit button is pressed, all the visible and non-visible upload bars are being uploaded to the server! This way we get our cheap multiple upload using a single upload bar method.

jQuery Single Multiple Upload File

I won't be displaying stickman code in this article as you can download directly from his website. We can now proceed with the coding after we have understand how stickman method works.

HTML code

All we need on the HTML section are these:

<div>
	<input type="file" name="files[]">
	<div id="upload_list"></div>
</div>

jQuery code

jQuery code is fairly simple. Let's don't complicate stuff. All we need to do is this.

jQuery(document).ready(function($){
var replaceMe = function(){
	var obj = $(this);
	$(obj).css({'position':'absolute','left':'-9999px','display':'none'}).parent().prepend('<input type="file" name="'+obj.attr('name')+'"/>')
	$('#upload_list').append('<div>'+obj.val()+'<input type="button" value="cancel"/><div>');
	$("input[type='file']").change(replaceMe);
	$("input[type='button']").click(function(){
		$(this).parent().remove();
		$(obj).remove();
	});
}
$("input[type='file']").change(replaceMe);
});

The above takes care of the basic. If you wish to restrict the number of upload, you can place a restriction variable.

jQuery(document).ready(function($){
var max = 2;
var replaceMe = function(){
	var obj = $(this);
	if($("input[type='file']").length > max)
	{
		alert('fail');
		obj.val("");
		return false;
	}
	$(obj).css({'position':'absolute','left':'-9999px','display':'none'}).parent().prepend('<input type="file" name="'+obj.attr('name')+'"/>')
	$('#upload_list').append('<div>'+obj.val()+'<input type="button" value="cancel"/><div>');
	$("input[type='file']").change(replaceMe);
	$("input[type='button']").click(function(){
		$(this).parent().remove();
		$(obj).remove();
		return false; //safari fixes
	});
}
$("input[type='file']").change(replaceMe);
});

Where max is the counter that restricts the number of uploads. Since jQuery takes care of most of the complicated things. The code eventually became smaller. For some reason bind doesn't works for the event change. Thus, i will have to attach the event again. From pure JavaScript of 156 line into a few line of codes, jQuery definitely makes developers life much more easier (doesn't means the code produce by jQuery is much more efficient though.).

The Demo

The demo can be found here.

Conclusion

The above jQuery code has simplify the version found on stickman site. Although the display doesn't looks as attractive but my objective has been achieved. Sometimes, JavaScript can be harder to read compared to a jQuery one. However, JavaScript version still has a better efficiency as compared to a jQuery one.

jQuery and JavaScript CSS !important

Everyone who is familiar with CSS !important statement understood that it means that the style have the highest priority regardless of other priority. However, !important should be avoided as much as possible and order priority should be practice in CSS instead. In jQuery, there are times when we need to change the styling of our web program but programmers usually lack of such knowledge and inquire whether !important is available for jQuery css() method. In this article, we will discuss jQuery css() and JavaScript methods in term of using !important definition.

jQuery CSS !important

One thing that everyone must have wonder (those that haven't tried yet) is whether jQuery support declaration of !important for their css() method such as this.

jQuery('#id').css('height', '200px !important');

You will find that nothing will happen with a declaration of such manipulation. If we were to try out on pure JavaScript with the above declaration, it will be something like this.

document.getElementById('id').style.height = "200px !important";

Having a pure JavaScript instruction such as this will not work in most browser other than safari 3++. Hence, jQuery will definitely won't work too. This is not a bug but something that most browser doesn't acknowledge a need since inline style already have the highest priority other than user defined ones. (unless you do not want your user to change how they view your website).

Solution to jQuery CSS !important

Well, the typical way of getting !important will not work. Rather, you might want to try CSS DOM cssText. Hence, you will force !important to your jQuery statement by doing this.

jQuery('#id').css('cssText', 'height: 200px !important');

However, most people will be unfamiliar with cssText. cssText will overwrites the css of that particular element. Hence, you will have to redeclare the rule for that particular element all over again. On the other hand, if you are using JavaScript cssText, different browser treat cssText different such as ie you will define this way,

document.getElementById('id').style.cssText = 'height: 200px !important'

While normally you will use it this way.

document.getElementById('id').cssText = 'height: 200px !important'

Definitely, there is a better alternative such as using the cssRules/rules array which can specify the rule in that element to be modify.

The other more practical way of doing it is by introducing new class for your element. Instead of styling through jQuery or DOM object which is applying inline styling (means highest priority already), you should leave every majority styling or best all of the styling to an external style sheet that help you reduce some bytes on the script and also improve maintainability for both your code and style. You can do this using the toggleClass which adds a new class to that element automatically.

jQuery('#id').toggleClass('classname');

or you can do this in JavaScript by replacing the class (this is more efficient than the jQuery one since there isn't any additional checking and stuff)

document.getElementById('id').className = 'classname';

Summary

Using !important in CSS is not advisable since it might kill your web usability. Furthermore, there is no reason why !important should be use as inline styling already has the highest priority. Hence, you might want to reconsider applying !important on your script after thinking about the consequences that might bought to your users.

8 jQuery Optimization Tips and Tricks

Its been quite a while since i write anything about jQuery. Furthermore, i have been writing many different optimization articles and jQuery is something that i have not write for quite sometime. Since many uses jQuery quite intensively in either design or application, why don't i give some tips on jQuery too. I think it will be beneficial that such optimization tips can be share and utilize in future application. Therefore, in this article you will see 8 jQuery optimization tips and tricks that might just benefit you during your jQuery coding.

1. Profiling

Once of the most important thing in every optimization, profiling. We can easily perform profiling using firebug. Everyone who is a developer or even designer should be well aware of firebug that could help assist in this task. Profiling allow us to see exactly how many times each function has run and how long does it take. With the help of profiling you will be able to see which function is the bottleneck in your jQuery functions.

2. Benchmarking

Another thing that every optimization will have to come across eventually is benchmarking. In programming, it is very common to use different ways to achieve the same result when we are writing our codes. In order to know which ways give us the best result, benchmarking will be required in order to justify correctly that certain way of achieving the same result is better than the other. Benchmarking across different JavaScript frameworks is the only way we can see which framework run faster than the other in certain ways. Hence, benchmarking is really required in order to justify the efficiency of two or more methods or script.

3. Specific Selector

In jQuery v1.3 below, specific a selector is necessary to optimize jQuery selector speed. A selector that are more specific will result in a faster result found. Hence, an id such as this:

jQuery('#someid').attr('value');

id is always the fastest compare to class or tag where classes is the worst (we do not have document.getElementByClasses don't we). Nonetheless, we can improve the efficiency of the selector by being more specific. Hence, instead of just calling out classes like this:

jQuery('.classes').html();

we can improve it by telling it where it exactly located at

jQuery('div ul li.classes').html();

By being specific in jQuery, we can improve the selector speed. However, this is what happen before jQuery v1.3. After the introduction of 'Sizzling' selector engine, this is no longer the case. We can see that by doing a selector test that the selector has speed up than before. This means that being specific with classes will not have significant differences after v1.3 (because it required more call to be specific) unless you are doing a rather odd selector such as this

jQuery('#id .class div').html();

It will be rather faster with just

jQuery(' .class').html();

Try to avoid id, classes and attribute combination that might just hit your selector badly. The point is to specific a selector but not over specific that might cause a degrade in selector performance.

4. Avoid Unnecessary Selector

Common subexpression elimination is a common way to optimize any programming code. Doing unnecessary selector is expensive. Doing something like this:

jQuery('.class').each(function(){
	jQuery(this).html();
	jQuery(this).find('div').each(function(){
		//etc.
	});
});

which required many selector it is best to use 1 instead since we are repeating ourselves and doing some redundant selector.

jQuery('.class').each(function(){
	var obj = jQuery(this);
	obj.html();
	obj.find('div').each(function(){
		//etc.
	});
});

This is something that we often see in many plugin. Many plugin contains unnecessary selector which degrade the perform of the plugin little by little.

5. Avoid Unnecessary Styling

This is another common mistake that many jQuery developer made. jQuery provides us with the ability to manipulate styling through styling methods. Although it is very convenient to do that but it also contribute to the size of the script and makes maintenance difficult. Furthermore, some of the selector is made solely for styling purposes which makes it even undesirable. To make thing worst, the styles made with jQuery are all inline style which doesn't help caching. Hence, instead of styling everything with jQuery. It is much more advisable to give classes to your tag and style it on a external stylesheet. Instead of writing jQuery styling such as these,

jQuery('div').each(function(){
	var obj = jQuery(this);
	obj.css({'background-color' : 'yellow', 'font-weight' : 'bolder', 'color': '#000', 'font-size': '15px'})
});

Where styling is being applied through jQuery, we can just add a class or even better do it on the HTML file itself!

jQuery('div').each(function(){
	var obj = jQuery(this);
	obj.addClass("mystyling");
});

This way we can easily eliminate a lot of extra code in our script. Unless, absolutely necessary to manipulate styling through jQuery, it is better to leave styling to the stylesheet.

6. Optimize Selector

We can also optimize our selector other than being a bit specific on our selector. The key to optimize our selector is simple. Naive JavaScript provides two method to get id and tag (getElementById and getElementByTagName). Hence, it is always faster to use tag or id on your selector. No matter what algorithm used for classes and attributes selection, the naive built-in JavaScript method will always have the upper hand. Nonetheless, classes and attribute selector have also been improved dramatically through the introduction of 'sizzling' selector engine. However, it is always advisable to reduce the number of attribute selector as they are the slowest in many cases. On the other hand, making your selector as simple as possible is good for pure tag and id selector but may not be true for attribute and selector. Hence,

jQuery('div')
jQuery('#id')
jQuery('.classes')
jQuery('p:last')

is considered as good selectors while the below might not give you very good selector result.

jQuery('body div div')
jQuery('div#id')
jQuery('#id div.classes')
jQuery('.classes p:last')

It is important to treat jQuery as a helper of JavaScript instead of a new language.

7. Avoid DOM Manipulation

Since we are using jQuery as a framework, making life difficult for ourselves is the most silly thing anyone can make. Example, using jQuery to write a table in DOM style~

var table = $('<table></table>');
for (var i = 0; i < 6; i++) {
  var tr = $('<tr></tr>');
  for (var j = 0; j < 7; j++) {
    tr.append('<td></td>');
  }
  table.append($tr);
}

Leaving aside the additional operation on append() each time we call, we are also doing some expensive DOM creation each step when we can really help ourselves by doing a one line query and leave the rest to jQuery. For customize table you might do this.

var table = '<table>'
for (var i = 0; i < 6; i++) {
  var tr = '<tr>';
  for (var j = 0; j < 7; j++) {
    tr +='<td></td>';
  }
  tr +='</tr>';
  table += tr;
}
table += '</table>';
var table = $(table);

For a static table, its really one line.

var table = $('<table><tr><td><td>...</tr><tr>...</tr>...</table>');

But if you really want a table, do it in HTML. You don't need to create everything using jQuery. Treat jQuery as an expensive action and use it when absolute needed. (same goes with styling)

8. Balance between JavaScript and jQuery

jQuery is excellent to speed up ANY front-end developer job. However, there are times when jQuery may take more time to perform certain action than using JavaScript. For example,

	css: function( key, value ) {
		// ignore negative width and height values
		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
			value = undefined;
		return this.attr( key, value, "curCSS" );
	}

The above is a CSS method in jQuery that takes a key and a value which we are familiar using in this way

jQuery('#id').css('display', 'block');

We can see that jQuery present certain overhead for doing something simple where JavaScript can also achieve.

document.getElementById('id').style.display = 'block';

Other methods such as show(), hide(), hasClass() and etc. also present some overhead which you should balance between complexity and efficiency. Hence, we must understand some of the cost of jQuery action and balance between JavaScript and jQuery. jQuery is build for general public and making a general public framework might means additional operation to meet everyone needs. Hence, if you truly going all out on optimization, you should consider the trade-off of some action between JavaScript and jQuery.

Summary

jQuery is a great framework that ease all our development life. Operation that gets complicated can easily become simple with jQuery. However, like i stress the important of keeping out unnecessary jQuery code will certainly help generating a more efficiency and optimize jQuery script.

The Predefined Prototype Object In JavaScript

Most of us learn JavaScript from tutorial website such as w3schools or tizag.com. However, these tutorial site only covered the most fundamental of JavaScript. Many hidden features of JavaScript are usual removed to simplify the tutorial. Although basic does bring us a long way, we still need to read more of these features eventually and improve our coding. In this article, i will cover the predefined prototype object in JavaScript. We will discuss everything we need to know about prototype object and the application in the real world.

The Prototype Object

The prototype object was introduced on JavaScript 1.1 onwards to simplify the process of adding or extending custom properties and methods to ALL instances of an object. In other word, prototype object is used to add or extend object properties or methods so every other object will also have such properties/methods. Let me show you an example. Below listed a few way to extend an object properties.

//adding a custom property to a prebuilt object
var imgObj =new Image();
imgObj.defaultHeight= "150px";

//adding a custom property to the custom object "Shape"
function Shape(){
}
var rectangle =new Shape()
rectangle.defaultColor = 'blue';

From the above example, we are able to extend properties of each object easily. However, if i create a new instances of the same object, the properties will be lost!

var newImg =new Image();
alert(newImg.defaultHeight); //return undefined 'defaultHeight';

var newRec =new Shape()
alert(newRec.defaultColor); //return undefined 'defaultColor';

This is when prototype object comes in. Prototype object is able to add the properties above and extend to other new instances object as well. Hence, the following will allowed all new instances created to contain the properties or methods attached by any previous object. We just have to add the keyword prototype between the object and name of the properties/method to use the prototype object. Using the same example above,

//adding a custom property to a prebuilt object
function check_height(){
 return typeof this.defaultHeight != 'undefined'?true:false;
}
var imgObj =new Image();
imgObj.prototype.defaultHeight= "150px";
imgObj.prototype.hasHeight= check_height;

//adding a custom property to the custom object "Shape"
function Shape(){
}
function color_checker(){
 return typeof this.defaultColor != 'undefined'?true:false;
}
var rectangle =new Shape()
rectangle.prototype.defaultColor = 'blue';
rectangle.prototype.hasColor = color_checker;

var newShape =new Shape()
alert(newShape.defaultColor) // blue
alert(newShape.hasHeight) // true

var newImg =new Image()
alert(newImg.defaultHeight) // 150px
alert(newImg.hasColor()) // true

Now every new instances of Image and Shape will have the properties and methods defined previously by the variables rectangle and imgObj.

Prototype Object Restriction

Prototype object can add or extend properties or methods to any custom object but for predefined object, only those that are created with the new keyword are allowed to use the prototype object in JavaScript. The following list some of these predefined object.

  • The date object
  • The string object
  • The Array object
  • The image object

Prototype Object is an Array

In case you haven't notice, prototype object is actually an array. From all of the above example, we are doing the following declaration to create new properties or method

//declare a function
obj.prototype.name = function(){};
//declare a property
obj.prototype.name = variables;

Notice that we are actually associating a name with a variable or function into the prototype object. Hence, we can also declare prototype with the same way as declaring an array.

obj.prototype ={
name: variables,
name: function(){}
}

The above two methods are similar and can be declare either way. Since both ways are similar, performance wise shouldn't make any big differences.

Priority Between Prototype And Own Property

What if we have both property? If the object itself already has a prototype property and if we redeclare the exact same property again without the keyword prototype, JavaScript will take which property? The answer is own property. In JavaScript, the own property takes precedence over the prototype's. Consider the following example,

function Rectangle(w,h){
	this.area = w*h;
}
var obj = new Rectangle(2,2); //area is 4;
obj.prototype.area = 200; // now we have own and prototype 'area'
alert(obj.area); // 4 will appear instead of 200; Hence, own property takes priority first.

What happened if we delete the property?

delete obj.area
alert(obj.area); // 200 appeared! 

Prototype property will take over again. Hence, we can use the Own property to overwrite prototype property defined in the object.

Identify Own and Prototype Properties

How do we identify whether the given object properties are from own or prototype? In JavaScript, there is a method hasOwnProperty which can be used to identify whether a given property is from own or prototype. Let's look at the following example,

function Rectangle(w,h){
	this.area = w*h;
	this.parameter = w+h;
}
obj.prototype.height = 5; 
obj.prototype.weight = 6; 

var obj = new Rectangle(2,2); 
obj.hasOwnProperty('area');// return true;
obj.hasOwnProperty('parameter');// return true;
obj.hasOwnProperty('height');// return false;
obj.hasOwnProperty('weight');// return false;

Inheritance Using Prototype Object

In the real world, prototype object is usually used as inheritance during OOP (Object Oriented Principle) with JavaScript. In JavaScript, we are not looking at classes inheriting other classes but object inheriting other object since everything in JavaScript is Object. Once we understand this, it will be easier for us to show inheritance example with prototype object.

function Shape(){
}
function color_checker(){
 return typeof this.defaultColor != 'undefined'?true:false;
}
function getArea(){
return this.area;
}

Shape.prototype.defaultColor = 'blue';
Shape.prototype.hasColor = color_checker;
Shape.prototype.getArea = getArea;

function Rectangle(w,h)
{
	this.area = w*h;
}

function Rectangle_getArea()
{
    alert( 'Rectangle area is = '+this.area );
}
Rectangle.prototype = new Shape();
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.getArea  = Rectangle_getArea; 

Using the custom object 'Shape' example above, i extend it so that 'Rectangle' will inherit all method and properties of 'Shape'. Inherit can be done through this sentence

Rectangle.prototype = new Shape();

'Rectangle' prototypes are assigned to the prototype of the 'Shape' through an object instance thereby "inheriting" the methods assigned to the prototype array of 'Shape'. After 'Rectangle' has inherit 'Shape', it overwrites the getArea method of 'Shape' through this statement.

Rectangle.prototype. getArea  = Rectangle_getArea; 

Inheritance using prototype object can reduce a lot of unnecessary coding and make your overall code run faster. The constructor on the above code is to overwrite the way Rectangle object is being instantaneous since the Rectangle prototype was overwritten by Shape prototype on the previous statement. Hence, to create a Rectangle object, the constructor for it will be as follow

function Rectangle(w,h)

We can use the above code as follow

var recObj = new Rectangle(20, 20);
rec.getArea(); //return 'Rectangle area is = 400'
rec.hasColor(); // return true;
rec.defaultColor;//return blue;

Check Prototype Inheritance

We can check whether a particular object is another prototype object by using the function isPrototypeOf. In other word, we can check whether a particular object inherit another object properties and methods. Using the previous inheritance explanation, we can check whether Shape is inherited into Rectangle object.

var rec = new Rectangle(5,5);
Shape.isPrototypeOf(rec);// return true;

This shows that Shape is a prototype of rec object. I think the method name said it all.

Tutorial: How To Sort An Array In JavaScript

In JavaScript, we are given a method Sort() to perform sorting. Although Sort() is said to be used for sorting an array, it can also be used to sort anything other than an array itself. In this article we will discuss all about JavaScript array.

Sort() in JavaScript

By default, the method Sort() in JavaScript takes a given array and sort it in lexicographical order and not alphabetical order! This means that the Sort() method sort a given array in dictionary order. Let's consider the following example of Sort method.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]

The above look fine when sorting an array of string but when it comes to number we will face a little problem.

var list =[ 39, 108, 21, 55, 18, 9]
list.sort() //[108, 18, 21, 39, 55, 9]

Looking at the result of the sort function seems to be unsorted but the fact that it is sorted according to lexicographical order does makes it in an ordered form after using the default sort method. Lucky, JavaScript doesn't force you to follow lexicographic order. You may also define a function to sort them in your own way.

Reverse Sort()

We get our result in lexicographical order after we performed a Sort() function. What if we want the reverse order of the sort function instead? In JavaScript, there is a function Reverse() which can help us to reverse the result of the array in the opposite order of the result. Consider the following example to illustrate Reverse() method in JavaScript.

var list =["Zebra", "Monkey", "Donkey"]
list.sort() //["Donkey", "Monkey", "Zebra"]
list.reverse() //["Monkey", "Zebra", "Donkey"]

Simple and powerful.

Customize Sort

The default Sort() function in JavaScript is quite simple and clear. Now, we will look at how we can customize this sort function. JavaScript Sort function does take in a parameter which is a function. Short to say, Sort() Method will sort your array instructed in the given function. However, the return value of the function must be as follow,

  • returns a value less than 0: parameter 'a' value is less than parameter 'b' value. 'a' come BEFORE 'b'.
  • returns a value greater than 0: parameter 'a' value is more than parameter 'b' value. 'a' come AFTER 'b'
  • returns exactly 0: parameter 'a' and 'b' have the same value. no change.

With the above rule, we can create a function that sort our array in numerical order instead of lexicographic order.

function sortmyway(data_A, data_B)
{
	if ( data_A < data_B ) // data_A come before data_B
		return -1;
	if ( data_A > data_B ) // data_A come After data_B
		return 1;
	return 0; // data_A == data_B, no change.

}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

The above example look good but the function seems to be a bit lengthy. You can change the comparison statement in a shorter form using the '?' symbol and we will get a shorter version of the code above.

function sortmyway(data_A, data_B)
{
return ((data_A < data_B) ? -1 : ((data_A > data_B) ? 1 : 0));
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) // [9, 18, 21, 39, 55, 108]

We can even shorten the above declaration to perform the same task as shown below,

function sortmyway(data_A, data_B)
{
	return (data_A - data_B);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[9, 18, 21, 39, 55, 108]

All the methods above sort the array in ascending order.

Sort Descending order

Using the shortest method i have above, i can declare a sorting function which sort in descending order as follow,

function sortmyway(data_A, data_B)
{
	return (data_B - data_A);
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[108, 55, 39, 21, 18, 9]

You can also achieve this by using the Reverse() method to eliminate the need to declare two sort function for ascending and descending order.

Random Sort Array

Well, we can also take advantage of the sort function to randomize our array. This way, we do not have to perform any loop which also contribute to function efficiency.

function sortmyway(data_A, data_B)
{
	return 0.5 - Math.random(); //random gives us result between 0 and 1
}
var list =[ 39, 108, 21, 55, 18, 9]
list.sort(sortmyway) //[21, 9, 39, 108, 18, 55]

Summary

Other than array, we can also sort unordered and ordered list. Sort() method in JavaScript can help us perform different kind of sorting in every type of element not restricting to array only. However, using JavaScript to perform sort of other element other than array can be a lot of pain. Personal advice is to use JavaScript framework such as jQuery or Mootools to ease the job. On the other hand, Sort() method can also be used to substitute unnecessary loop to create a more efficient code especially when comparing each element in an array is required. (we just have to eliminate the return value to perform such task) . Even eliminating duplication in an array is possible with Sort() method!