Archive for the ‘articles’ Category

jQuery and Drupal

So I’ve decided to write an article for all the Drupal webmasters. If you never heared of Drupal, well Drupal is a free and open source content management system (CMS) written in PHP . It is used worldwide, ranging from personal blogs to large corporate and political sites including and

Important: A very useful Drupal php function is drupal_add_js(), with this function we can include a javascript file in the head section of the html output.

jQuery can be used when developing functionalities under the Drupal CMS because jQuery is part of the Drupal core since Drupal 5.
Read more

Speeding Up Your Web Site

I decided to write a different topic article, about performance techniques, just to keep things interesting. So this article will not be about jQuery especially but a general tutorial about how to improve your web site performance ( a thing that I found is very important).  I will try to make a list will all the best practices when it comes to web page optimization.

1.Minify javascript and css
The performance of a web page can be increased if the javascript and css is compressed.When code is minified comments are removed, white spaces, and in case of javascript a base64_encode can also be used.The resulting file will decrease in size. Tools that can be used are JSMin and YUI Compressor.Also a lot of free tools can be found on the internet.These is how a compressed js code will look like:

  1. eval(function(p,a,c,k,e,r){e=String;if(!''.replace(/^/,String)){while(c)r[c]=k[c]||c;k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('1 2(3,0){4("5.6 = 7;",0)}',8,8,'b|function|timedRedirect|a|setTimeout|location|href|redirectTo'.split('|'),0,{}))

2. Flush the head
When a request is made, the browser has to wait for the html content to be received from the server before it can start retriving js files, css files , images, etc. So a good practice is to flush the head part of the html before so the browser can start retrieving the js,css files.

  2. < ?php flush(); ?>
  3. <body>
  4. </body>

3. Split Components Across Domains
By splitting you can maximize parallel downloads. By standard a browser will not make more then 2 request at a time, so if you have 10 images on a page it will get the first 2, then the next 2 and so on.By splitting on multiple domains you will resolve this issue. Make sure you’re using not more than 2-4 domains because of the DNS lookup penalty. As an example, you can host your main html/dynamic content on and move static components(images,css files, js files) on and

Read more

jQuery and HTML5

As probably most of you know HTML 5 is currently under development as the next major revision of the HTML standard and is expected to be the next step that will change how the web looks.

I will try to show you a couple of the new things added in HTML5 and how much jQuery influenced the HTML5 development.

So what is new:

New selectors

-Finding elements by class:

  1. document.getElementsByClassName("test");

-Finding elements by CSS syntax – very similar with jQuery selectors

  1. document.querySelectorAll("table.test > tr");

Drag and drop

  1. document.addEventListener('dragstart', function(event) {
  2.    event.dataTransfer.setData('text', 'Customized text');
  3.    event.dataTransfer.effectAllowed = 'copy';
  4. }, false);

In this HTML5 javascript example you can see the callback style use like in jQuery.

Web Workers

  1. main.js:
  2.   var worker = new Worker('extra_work.js');
  3.   worker.onmessage = function(event) { alert(; };
  5. extra_work.js:
  6.   self.onmessage = function(event) {
  7.     // Do some work.
  8.     self.postMessage(some_data);
  9.   }

So we will have easy-to-use multi-thread support in HTML5.

Web Storage

  1. // use localStorage for persistent storage
  2. // use sessionStorage for per tab storage
  4. textarea.addEventListener('keyup', function () {
  5.   window.localStorage['value'] = area.value;
  6.   window.localStorage['timestamp'] = (new Date()).getTime();
  7. }, false);
  8. textarea.value = window.localStorage['value'];

Session support in Javascript.

Read more

How to create a jQuery plugin

For all you jQuery lovers out there I will try to show you how you can create your own jQuery plugins, so you can start developing new and interesting stuff for all the jQuery community.

To create a jQuery plugin, and have it integrated in the jQuery object, we have to attach a function to the jQuery prototype.The prototype property in JavaScript can be used to extend any object with new methods or properties.

Before adding you plugin your function you must wrap it, by creating a private scope for jQuery, like this:

  1. (function($) {
  2. //Your code
  3. })(jQuery);

Now let’s say you want to create a jQuery plugin with the name “test”. You must add your “test” method to the jQuery object by attaching it to $.fn (which is an alias for the prototype property of the jQuery object “jQuery.fn = jQuery.prototype“). So this is how your plugin should look until now:

  1. (function($) {
  2. $.fn.test = function() {
  3. // Your code
  4. }
  5. })(jQuery);

Read more

Verify if an element exists using jQuery

A common and sometimes overlooked question is how to verify if a DOM element exists using jQuery. This can be done very easy using the length property:

  1. if (!$('#example').length)
  2.    alert("Element not found");

So.. if the length property is larger than 0 then the element exists. A common mistake that people tend to do is to use !$(‘#example’), but this is wrong because jQuery will return an object even when not finding the requested DOM element.

jQuery and YQL

A couple of weeks ago while working on a project  I came across something very interesting, something called YQL ( Yahoo Query Language). YQL is a free service offered by Yahoo and it’s a very powerful tool for working with web services and doing all kind of interesting things like: data scraping, data insertion/updating and other cool and highly powerful things. YQL offers the possibility of creating different query’s over different web services and then retrieving the data in an easy to use XML or JSON format.

Here is how a YQL query looks like (this returns all flickr photos that contain “Cat” with a 10 limit) :

  1. select * from where text='Cat' limit 10

An other good functionality for YQL is data scraping, here is an example (this will find all ‘a’ tags from a specified xpath) :

  1. select * from html where url='' and xpath='//body/p/a'

Ok. So now lets say that we want to add the data from the previous example in out page using jQuery.This is how it should be done:

  1. $.ajax(
  2.          {
  3.       type: 'GET',
  4.              url: "*%20from%20html%20where%20url=''%20
  5. and%20xpath='//body/p/a'&format=json",
  6.              dataType: 'jsonp',
  7.       success: function(data, textStatus)
  8.       {
  9.                 $('body').append(data.query.results.a.content);
  10.        }
  11. });

For help with creating your own YQL queries use the Yahoo YQL Console:

For easy-to-use YQL queries i suggest using the YQL jQuery plugin :

After you install the YQL plugin this is how it can be used to replicate the example presented before:

  1. $.YQL("select * from  html where url='' and xpath='//body/p/a'",function(content){
  2.           $('body').append(content.query.results.a.content);
  3. });

jQuery 1.4 Cheat sheet

With the release of jQuery 1.4.1, I thought a cheat-sheet is required to help with your development. So…here it is:

Read more

Google CDN (Content Delivery Network) for jQuery

A new service from google for including the jQuery library is the Google Content Delivery Network (CDN). A Content Delivery Network is a network of servers that serve content in a fast and scalable manner, distributed geographically, each request being served by the closest server in the network.

So, instead of hosting the jQuery files on our own web server we have the option of letting Google serve the jQuery file. You benefit from the speed and reliability of Google’s vast infrastructure, with the added bonus of the option to always use the latest version of jQuery and that because of the use of this service by many webpages the file will be cached (this means better speed for the users).

This is how to include:

  1. <script src="" type="text/javascript"></script>

JavaScript Namespacing

I’ve learned from experience that when programming javascript namespacing is a very important technique for keeping a clean code.

By definition the main goal of namespacing is avoiding collisions, but namespacing also helps in keeping a nice and clean code.By separating your code using namespacing easy to use packages of code can be created.
This is how to declare a variable and a function in a “my” namespace:

  1. var my = {};
  2. var my.url = '';
  3. var my.sayHello = function (){
  4. alert('Hello');
  5. };

To call sayHello just:

  1. my.sayHello();

I recommend using namespacing in your implementation of javascript code.

Event delegation in Javascript (jQuery)

Event delegation.What is event delegation and why do we need it?…First of all a small recap on event handlers.  If we want to add an onclick event handler for all paragraphs in a document, this is the instruction in jQuery:

  1. $('p').click(function(){/* Code here */})

By doing this we add an anonymous function as a handler for the onclick event.

Before explaining event delegation you must know that as of version 1.4.1 jQuery has support for event delegation with the function live().

Event delegation makes use of two overlooked features of JavaScript events:event bubbling  and the action target. When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s parents.The event target hold’s the originating element (the button in our example).

Read more

Return top