Wanna learn jQuery but don’t know where to start from? – The events

In the first lecture on Jquery we introduced the basic concepts of this framework and we made a simple example which consisted of adding a class to highlight certain sections of the text once the loading of the page ends.

Naturally, in the real world, you may want to apply such an effect only upon request, or only under certain circumstances. It is under these circumstances that we have to introduce the concept of event.

What is an event?

We can define an event (in JavaScript) as whatever interaction of the user with a web page. The actions that can be performed are multiple: click, double click, window resizing, passing of the mouse on an item; to each of these events it is possible to associate a more or less complex effect.

It is more or less like in the real world: press an interrupter (event) and the lamp turns on (effect).

How to switch on a lamp with jQuery?

Let’s create a simple lamp interrupter with the help of jQuery. Let’s create the HTML structure:

<!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>Lamp</title>
      <link rel="stylesheet" href="lamp.css" type="text/css" media="screen">
      <script src="jquery.js" type="text/javascript"></script>
      <script src="lamp.js" type="text/javascript"></script>
   </head>
   <body>
      <div id="interrupter">
         <a href="#" id="on">Turn Lamp On</a>
      </div>
      <div class="lamp">
      </div>
   </body>
</html>

The structure is very simple: a link with ID “on” for “switching on” the lamp and an empty div which will host the image of the object. As you can see the link doesn’t aim to any file: in fact, no external interaction to the page is necessary. Everything occurs using JavaScript, through jQuery.

In the head section I have inserted the link to the framework (jquery.js), the link to an empty JavaScript file (lamp.js) and to a CSS file which will contain the following code:

body{
  font-family:Helvetica,Arial,sans-serif;
  width:500px;
  margin:0 auto;
}

.lamp {
  width:150px;
  height:273px;
  background:#CCC url(lamp.png) top left no-repeat;
  margin:0 auto;
}

#interrupter {
  margin: 20px;
  text-align:center;
}

.on {
  background-color:#f8f070;
}

Besides some purely aesthetic solutions, I have loaded the background image for the “lamp” div (which you can find here) and created a class which will “turn on” the lamp.

After preparing the terrain, we finally pass to the jQuery code.

Linking the events

Open then the file “lamp.js” in your preferred editor. As in the example of the previous lesson, we want the effects to be available only after the structure of the document has loaded. Thus, the first thing to do is inserting these code lines:

$(document).ready(function(){
});

The entire code we want to execute in the page, will be comprised in this block. The jQuery function that deals with linking an event to an effect is called “bind”. This function takes as required input parameters, the type of event, and with the function to execute when this event occurs.

.bind("type of event","function to execute")

The complete list of available events can be found in this section of jQuery’s documentation. The most used ones are “click”, “dblclick”, “submit”, but each one has its own utility.

Naturally the bind function has to be applied to a previously selected item, through the $ operator. In our case it’s the link with ID “on”:

$(document).ready(function() {
  $("a#on").bind("click",function(){
    ...code to execute at the click...
  });
});

The code can be read as “After the document has been loaded, links the event click on the link with ID “on” and execute the code present in the function passed as parameter”

At this point we only have to apply the class “on” to the div in order to have a functioning interrupter:

$(document).ready(function() {
  $("a#on").bind("click",function(){
    $("div.lamp").addClass("on");
  });
});

Obviously, this lamp is destined to be always on like this. It would be useful, as an exercise, to add a link for switching it off, reminding that the “removeClass” function exists. This should be the final result.

The code can be rendered lighter through some abbreviations. In fact, given that obtaining a click on an item is a frequent operation, the creators of jQuery have introduced an alias for all events of the “bind” function. In this example we will use the “click” function and the code becomes:

$(document).ready(function() {
  $("a#on").click(function(){
    $("div.lamp").addClass("on");
  });
});

Conclusions

In this lesson we introduced the managing of events in jQuery, seeing that it is a simple application, which however demonstrates the power of this framework (we have written three lines of code only!). In the next lesson we will improve this example through the use of “Interaction Helpers” and in addition we will take a look at the effects present in jQuery.

      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:

      2 comments

      Trackback e pingback

      1. You want to learn how to use jQuery but don’t know where to start? | Your Inspiration Web
        [...] Lesson 2: the events (basic concepts) [...]
      2. Wanna learn jQuery but you don’t know where to start from? Inline styles, predefined effects | Your Inspiration Web
        [...] Lesson 2: the events (basic concepts) [...]

      Leave a Reply

      Current month ye@r day *