To know CSS is almost to know jQuery

jQuery would be nothing without the power of CSS. Much of the great success of this popular framework comes from the unique mix of JavaScript routines and CSS syntax combined with a form of beautiful fusion that makes this duo incredibly powerful. I'm not talking about a simple getting and setting CSS styles on web elements. I'm talking about how deeply the simplicity of CSS has influenced jQuery. For example, if I want to stylize the very first a element of a paragraph, in CSS you have p a:first-child and in jQuery $('p a:first-child'). Did you notice the resemblance in their syntax? So if you know how to select elements in CSS, you actually know how to select them in jQuery.

Another point is the complete separation of behavior and style, that is, jQuery code and CSS code. In fact, jQuery allows you to keep your styles in separate CSS classes and then add them when required. For example, you want to display validation errors prior to form submission. To accomplish this task, you want to add some styles to the form field where an error has occurred. First, you define your CSS class that will handle such error:

.validation-error {
  background: #ffffe0;
  border: 1px solid #c00;
}

Then you can add jQuery:

$('input.required').each(function() {

    var $input = $(this);
    
    if(!isValid($input)) {
    
       $input.addClass('validation-error');
       
    }

});

Another application field of CSS styles is animations. The jQuery's animate() method accepts as its first parameter an object literal containing CSS property/value pairs. Suppose that you want to make a link larger when a user clicks on it. Here's how you can do:

$('a').click(function() {

    
    $(this).animate({
      fontSize: '1.2em',
    }, 'slow');


});

If you want to read or set your styles, jQuery provides a useful method called css(). This method is either a setter or a getter. The interesting thing here is that jQuery handles for you all the browser discrepancies with handling styles in JavaScript, so the result you'll get is always accurate.

Finally, if you want to get started, a good starting place is surely http://docs.jquery.com. Always remember that if you already know CSS, you almost know jQuery.

Leave a Reply

Note: Only a member of this blog may post a comment.