You want to learn how to use jQuery but don’t know where to start?


Considered by a majority of developers nothing more than a hobby until a few years ago, thanks to the Ajax technology, Javascript has been reliving its golden days once again. Thanks to the ever-widening diffusion of this language, a great number of Javascript libraries have sprung up that allow a user to execute the most difficult of functions, such as being able to eliminate some elements through a fade-out process as well as real-time validation of a field where text is imputed. Let’s learn more about one of the most famous libraries: jQuery.

What’s jQuery?

jQuery is a JavaScript framework, in other words it is a bundle of Javascript functions which facilitate the most common processes, allowing developers to concentrate on the logic of a website instead of on the technical aspects of building a website.

One characteristic that distinguishes jQuery from other frameworks is that, instead of having complex paradigms used in advanced programming, jQuery contains both CSS and HTML. As a result, even the most inexperienced webdesigners can find themselves at ease and apply various effects to their own creations.

Download and installation

Let’s download the latest version of jQuery from the official website, making sure to choose the file “Development” which is an uncompressed, readable file. The compressed version will become useful at a later stage when it is used on the production server. It is important to note that the “Production” version takes up only 19KB of space, which allows the framework to be extremely portable and light.

As for us, it’s helpful to know that installation is not necessary, it is enough to include the file “jquery-versione.js” in the Html documents as shown below:

<script src="jquery-1.3.2.js" type="text/javascript"></script>

A practical example

Let’s start with an example. Using an Html document with content (in this case, we are going to use the opening words of “Pinocchio” from the LiberLiber website):

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Prova con jQuery</title>
<link rel="stylesheet" href="stile.css" type="text/css" media="screen" />
<script src="jquery.js" type="text/javascript"></script>
<script src="prove.js" type="text/javascript"></script>
</head>
<body>
<h1>Come andò che maestro Ciliegia, falegname, trovò un pezzo di legno, che piangeva e rideva come un bambino.</h1>

<p>C'era una volta...</p>

<span>- Un re! - diranno subito i miei piccoli lettori.</span>

<p>No, ragazzi, avete sbagliato. C'era una volta un pezzo di legno.</p>

</p>Non era un legno di lusso, ma un semplice pezzo da catasta, di quelli che d'inverno si mettono nelle stufe e nei caminetti per accendere il fuoco e per riscaldare le stanze.</p>

<p>Non so come andasse, ma il fatto gli è che un bel giorno questo pezzo di legno capitò nella bottega di un vecchio falegname, il quale aveva nome mastr'Antonio, se non che tutti lo chiamavano maestro Ciliegia, per via della punta del suo naso, che era sempre lustra e paonazza, come una ciliegia matura.</p>

<p>Appena maestro Ciliegia ebbe visto quel pezzo di legno, si rallegrò tutto e dandosi una fregatina di mani per la contentezza, borbottò a mezza voce:</p>

<q>Questo legno è capitato a tempo: voglio servirmene per fare una gamba di tavolino.</q>

<p>Detto fatto, prese subito l'ascia arrotata per cominciare a levargli la scorza e a digrossarlo, ma quando fu lì per lasciare andare la prima asciata, rimase col braccio sospeso in aria, perché sentì una vocina sottile, che disse raccomandandosi:</p>

<q>- Non mi picchiar tanto forte!</q>

<p>Figuratevi come rimase quel buon vecchio di maestro Ciliegia![...]</p>
</body>
</html>

to which we apply a simple style sheet:

body{
font-size:small;
font-family:Helvetica,Arial,sans-serif;
line-height:1.3;
}

h1{font-size:150%}

.highlight{
background-color:#FFF6BF;
font-style:italic;
}

All we did here was to stylize the text and title, as well as creating a “highlight” class, with a yellow background and cursive text.

As you can see, we’ve added a link to two JavaScript files: “jquery.js” and “prove.js“. The first one has been renamed after being downloaded from the website jquery.com, while the second one is the one which we will work on.

It might seem strange that all these files are needed for a simple example such as this one; however you must know that this is the right way to operate. As a matter of fact, in this way we are able to completely separate the structure (HTML) from the presentation (CSS) and from the behavior (JavaScript).

We could have included the CSS styles as well as the JavaScript code in the HTML document, but separating the various aspects is advantageous for it provides a much more flexible and functioning structure.

Main concepts of jQuery

The main function of jQuery is to select an element on a certain page and to make it perform an action, whether it is to hide, highlight, or change any of its characteristics.

jQuery’s strength lies in the fact that this selective function takes place using the preexisting tools available to any webdesigner: CSS selectors.

The main construct is based on the dollar sign “$which is an alias of the jQuery function.

Brieftly stated, in order to select a bundle of elements we can write:

$("selector")

or:

 jQuery("selector")
 

We can use every known combination of available selectors that have a CSS specification, even if they are not supported by the browser in question. This is another peculiarity concerning jQuery: it provides a very abstract level that allows to cancel the existing differences between various web browsers.

For example we can write:

 $("div#content > p")
 

Let’s select all of the paragraphs listed under div “content”; this code also works on a browser that does not support the child (>) selector, only if JavaScript is enabled.

A first try of jQuery

Let’s go back to our example. We have a document that has been applied with various CSS styles. What we want to do here is to apply dynamically the “highlight” class to the elements “q” during the time of loading.

Open an empty file from your favorite editor and save it as “prove.js”. Afterwards paste or copy the following code:

$(document).ready(function() {
 $("q").addClass("highlight");
});

This is all that you need: three lines of code! However, even within these three lines of code, there are some interesting concepts that need to be emphasized:

  • The code is executed only when the whole document tree has been loaded: in order to achieve this we can treat the document as an object of the dollar $ function, then apply the “ready” method (you will discover that all of the methods in JavaScript are used by adding a point and the name of the method).
  • As part of the “ready” method, let’s write up a function with no name:
    function() {
    ....
    }
    

    All of the code found inside the two brackets will be executed afterwards, when the page is loading.

  • Let’s select all of the “q” elements using the $ operator. Then we can apply the addClass method, which as the name suggests, adds a class to the selected object. In jQuery all of the methods are given a name which is self-explanatory, for instance we have a method .removeClass() that removes a class from an object.

An important characteristic of jQuery is its ability to link together various methods: in the previous example we could have written :

$(document).ready(function() {
 $("#element").addClass("class1").addClass("class2").addClass("class3");
});

Thus adding class1, class2 and class3 to #elemento.

Conclusion

In this article we have just scraped the surface in regards to discovering the full potential of this library. Nevertheless, we can already start to create a series of dynamic websites, without much difficulty, referring to the fundamental concepts covered in this guide as well as on the excellent online documentation.

Master per Web Designer Freelance
In tutti questi anni abbiamo ricevuto centinaia di richieste di approfondimento sulle numerose tematiche del web design vissuto da freelance. Le abbiamo affrontate volta per volta. Ma ci siamo resi conto che era necessario fare qualcosa di più. Ecco perché è nato One Year Together, un vero e proprio master per web designer freelance che apre finalmente le porte al mondo del lavoro.
Scopri One Year Together »
[pdf]Scarica articolo in PDF[/pdf]
Tags: , ,

The Author

Fond of web design, takes delight in creating (X)HTML+CSS layouts. A maniac of polished and tidy codes, the type of person you find in your house straightening the paintings hanging on the wall. He has made his mind of becoming a web designer with a capital “w”, and spends entire nights awake in order to make his dream come true.

Author's web site | Other articles written by

Related Posts

You may be interested in the following articles:

5 comments

Trackback e pingback

  1. Tweets that mention You want to learn how to use jQuery but don’t know where to start? | Your Inspiration Web -- Topsy.com
    [...] This post was mentioned on Twitter by Your Inspiration Web, Sergio Arantes. Sergio Arantes said: You want to learn …
  2. Wanna learn jQuery but don’t know where to start from? – The events | Your Inspiration Web
    [...] Lesson 1: introduction and first basic concepts [...]
  3. Wanna learn jQuery but you don’t know where to start from? Alternating functions, variables, first effects | Your Inspiration Web
    [...] Lesson 1: introduction and firs basic concepts [...]
  4. Want to learn jQuery but you don’t know where to start from? Custom animations | Your Inspiration Web
    [...] Lesson 1: introduction and firs basic concepts [...]
  5. Wanna learn jQuery but you don’t know where to start from? Inline styles, predefined effects | Your Inspiration Web
    [...] Lesson 1: introduction and firs basic concepts [...]

Leave a Reply

Current month ye@r day *