A gentle introduction to jQuery for CSS developers

A gentle introduction to jQuery for CSS developers

A simple introduction to the jQuery library for CSS developers.

Most CSS developers are simply afraid of jQuery and JavaScript in general. They think they have not enough programming skills to get to the bottom of it and write proficient and fluent code. Well, simply put, you're totally wrong. Before jumping to the wrong conclusions, you should get an overall idea of how jQuery and JavaScript work. You'll be probably very happy to find out that you can actually write your own scripts without having a degree in computer science. Don't you believe me? Well, let's see some examples.

Goodbye DOM methods, hello selectors!

jQuery selects elements based on CSS selectors, practically the same selectors you use on your style sheets. Before jQuery broke into the web scene five years ago, you had to use DOM methods to get your elements. Five years ago, you were forced to write something like that:


var li = document.getElementById('list').getElementsByTagName('li');

In other words, you were forced to learn the DOM. With jQuery you can now write this instead:


var $items = $('#list li');
var items = $('li', '#list');

This is exactly as writing in your CSS:


#list li {  }

Further, jQuery provides also custom CSS selectors that are not part of any CSS specification but they turn out to be very handy. Let's say that you have to select all the headings in a document. With the traditional DOM approach, this is a very tedious task. And with jQuery:


var headings = $(':header');

Is that all? Yes indeed! Instead, using CSS requires a little bit more typing:


h1, h2, h3, h4, h5, h6 {  }

The $() wrapper

All the jQuery's magic is done through the $() wrapper, which is an alias for jQuery(). This method performs all the work required to turn an expression to a matched set of elements. Every jQuery's chain starts with this wrapper.

You can pass to this wrapper not only CSS selectors, but also the old good DOM methods:


var $test = $('#test');

var test = $(document.getElementById('test'));

The above expressions perform the same operation: they select an element with an ID equal to test.

When the DOM is ready you gotta be ready

In the bygone age of the WWW, the DOM didn't exist formally. It was only in 1998 and later in the very first years of the century that the W3C decided to put the word end on the useless fights between browsers and standardized the Document Object Model, aka the DOM.

The DOM is a tree-based document structure where each element, its contents and attributes are called nodes. Elements are structurally organized by following a strict relationship between parents, children and ancestors. is the same relationship you can find in the CSS specifications.

For example:


p:first-child { }

In the DOM, you have the firstChild property attached to every element.

The problem with the DOM is that it's not always ready to be used in your scripts. That's due to the fact that a browser must load all the dependencies of a document before giving you access to the DOM. jQuery allows us to know when the DOM is fully constructed and ready with the following expression:


$(document).ready(function() {

 // your code here

});

Now you can execute your code right on time!

Events happen

Every good CSS developer knows that elements can actually have states. You have an :hover state, a :focus state and so on. In the jQuery terminology, these are called events because they happen when a user interacts with your document or when the document changes its initial state.

In other words, a jQuery event is something that happens when something else happens.

Events can be handled through event handlers. Event handlers are pieces of code that are executed only when a particular event occurs. For the rest of the life cycle of your code, these handlers simply wait for an event. They're idle. And patient.

For example, given a div element with an ID test, you can display an alert box when such an element is clicked:


$('#test').click(function() {

 alert('Hello, world!');

});

Another example is the inline validation of input text fields when they lose focus:


$('input').blur(function() {

 var value = $(this).val();
 
 if(value == '') {
 
  alert('Empty fields not allowed.');
 
 }

});

The jQuery's on() method allows us to define our custom events as simple but powerful inline functions. A custom event has a name (specified between quotes) and a callback function that defines its behavior. Custom events can be invoked using the trigger() method.

Suppose that we want to attach a custom event only to animated elements whose CSS positioning is either relative or absolute. Here's how we can do:


 var counter = 0;

  $('#test').on('animating', function() {
  
    
    counter++;
  
    if($(this).is(':animated')) {
    
      if($(this).css('position') != 'static') {
      
        console.log('Animation ' + counter );
      
      }
    
    }
  
  });

Our event is called animating and we can use it as follows:


$('#test').click(function() {
  
    
  
    $(this).animate({
      left: 100
    }, 'slow', function() {
    
      $(this).trigger('animating');
      
      $(this).animate({
        left: 0
      }, 'slow', function() {
      
        $(this).trigger('animating');
      
      });
    
    });
    
  
});

Animations in motion

CSS3 introduced the concept of CSS animations and transitions. jQuery comes equipped with a powerful set of animation methods, plus the arsenal provided by its plugins.

jQuery's animations are different from CSS animations and transitions. In fact, jQuery allows you to control every aspect of an animation and, at the same time, provides a way to extend its base animations and effects.

CSS3 allows you to do the following:


a#test {
 position: absolute;
 top: 0;
 left: 0;
 width: 100px;
 -moz-transition: all 1s ease-in-out;
 -webkit-transition: all 1s ease-in-out;
 -o-transition: all 1s ease-in-out;
 -ms-transition: all 1s ease-in-out;
 transition: all 1s ease-in-out;
}

a#test:hover {
 top: 50px;
 left: 50px;
 width: 150px;
}

In CSS, you cannot change the default effect set provided by the CSS specifications.. Well, jQuery can, thanks to its ability to extend its core Effect object (with the Easing plugin):


$('a#test').mouseover(function() {

 $(this).animate({
  top: 50,
  left: 50,
  width: 150
 }, 1000, 'easeInQuad');

});

Choosing plugins

Choosing a jQuery plugin is surely more difficult than using it. There are thousands of jQuery plugins on the web that perform a wide range of tasks but only a few of them are really useful and usable. The overwhelming majority of jQuery plugins make you feel frustrated because we usually spend a significant amount of time trying to make them work but without results. Sometimes we feel stupid, other times we simply trash the plugin and start another Google search. That's because such plugins were not designed with usability in mind. Usually we define a plugin poor when it doesn't satisfy all the jQuery coding guidelines. This can be misleading, because even a poorly written plugin can turn out to be the right plugin to us. It's not about coding: it's all about usability.

First of all, a jQuery plugin should be well-documented. Being well-documented doesn't simply mean listing all the default options with their values. Instead, it means that every option (or option combination) should be documented and have a demo page. Demo pages must be atomic and not too complex. One should grasp how an option works by simply viewing the corresponding demo page. For example, Cycle is well-documented whereas scrollTo is not. In fact, scrollTo puts every possible option into a single demo page, thus making life harder for plugin users. I spent 3 (3!) hours trying to figure out how scrollTo works!

Documentation has nothing to do with JavaScript or JSDoc comments: plugin authors should provide a detailed documentation as separate HTML pages. Unfortunately, the jQuery community mostly focuses on code quality without taking this aspect into proper consideration. Instead, this aspect is crucial because a plugin user could not spend hours to make a plugin work.

Further, code snippets should be provided as an aid to users. Generally, plugin authors assume that you will view the source of the page to see how the plugin works. This is another useless waste of time: we need that code because our client asked us to add another cool effect to the site and we simply do not have the time to scroll the source code! Authors should include code snippets on every demo or documentation page for the sake of a copy and paste made in a hurry.

Plugins, however, should be flexible. Plugins that are bound only to a particular HTML element are surely useful, but only for one specific task and only on a specific element. For example, a slideshow plugin should work either on a div or a ul. That's because sometimes we work on the markup chosen by other developers (e.g. PHP developers who have implemented a template system) and we have to adapt our code to that markup.

Flexible plugins are also plugins that not only fulfill a specific task now in the present but are also capable of being used in the future for other tasks. For example, a Twitter plugin may be used now only to fetch the latest tweets, but in a not too distant future it should allow us to format Twitter dates or to compute the time elapsed between each tweet.

In a nutshell: flexibility and usability are the signs of a plugin that is right to us.

Document yourself

The only web site I recommend to beginners is the official documentation of the jQuery library, where you can find a gigantic variety of useful resources.