Wanna learn jQuery but you don’t know where to start from? Alternating functions, variables, first effects

In last week’s article we created a simple lamp interrupter. In this lesson we will proceed with the optimization and improvement of this example, illustrating new functionalities of the jQuery framework.

Let’s proceed with no delay!

Alternating more actions: the toggle function

Obviously, a normal interrupter does not contain a switch for switching the lamp on and one for turning it off: everything is included in a single device. Let’s try then to optimize our jButton! What we want to obtain is a unique link which switches the lamp on and off, depending on its state.

Theoretically speaking, we might need a construct like this “At my click if among the link attributes the class ‘on’ is not there add it, otherwise remove it.

If you are familiar with programming, you should have already understood that what we might need is the if-else pair, however jQuery provides a more elegant function fit for this scope: the toggle function.

toggle(function1, function2, [function3], [function4],...)

Toggle enables us to alternate between two or more functions at the click of the mouse, taking care of “recalling” the state of the object that changes. We can thus modify the code, eliminating a HTML link:

<!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="interrupter">Turn Lamp On</a>
    </div>
    <div class="lamp">
    </div>
  </body>
</html>

and inserting in the file lamp.js

$(document).ready(function() {
  $("a#interrupter").toggle(
  function() {
    $("div.lamp").addClass("on");
  },
  function() {
    $("div.lamp").removeClass("on");
  });
});

In this way, by clicking on the link the on class is added and removed from the div which contains the lamp, enabling us to switch it on and off. However, there’s a problem: the text of the link always remains “Turn Lamp On”, no matter if the latter is switched on or off. We have to change during the execution the text of the link, in such a way it changes accordingly depending on the state of the lamp.

This time jQuery’s HTML function comes to our aid. This substitutes the text inside an item with the one specified inside the JavaScript file, and is used in this way:

$("item-to-select").html("text to insert in the item")

For example, if we had a paragraph:

<p id="speech">Friends and brothers who are here tonight, I will be brief...[long speech as much as one likes]</p>

with these code lines we can change the text:

$(document).ready(function() {
  $("p#speech").html("Friends and brothers, prepare for a good nap...[long speech as much as one likes]");
});

Let us see how to apply everything to our jButton. We want the text inside the link with ID “interrupter” becomes “Turn Lamp Off” when the later is on, otherwise it becomes “Turn Lamp On”. We can thus modify the JavaScript code:

$(document).ready(function() {
  $("a#interrupter").toggle(
  function() {
    $("div.lamp").addClass("on");
    $("a#interrupter").html("Turn Lamp Off");
  },
  function() {
    $("div.lamp").removeClass("on");
    $("a#interrupter").html("Turn Lamp On");
  });
});

The result, is more than satisfying.

Optimizing the code: the variables

As you can see, our code contains some repetitions. And repetitions, when it comes to programming, are never a good thing. What would happen, if for whatever reason, we change the ID from “interrupter” to “button”? We have to modify the JavaScript code in three different points and this, for a project consisting of hundreds of code lines, would easily lead to errors and inconsistencies.

We can easily fix this situation with the variables. In practice variables are containers: they can contain texts, numbers or more complicated items. The interesting thing is that a variable, once defined, it can be reused many times. As always, an example is worth more than a thousand words:

$(document).ready(function() {
  var interrupter = $("a#interrupter");
  interrupter.toggle(
  function() {
    $("div.lamp").addClass("on");
    interrupter.html("Turn Lamp Off");
  },
  function() {
    $("div.lamp").removeClass("on");
    interrupter.html("Turn Lamp On");
  });
});

In the previous code we saved the value $("a#interrupter") in the variable interrupter using the syntax:

var nameVariable = text/number/object_to_save_in_the_variable

We then used the variable instead of the selector. You can object that repetition is still there. In the end we have added a line of code and repeated the word “interrupter” thrice. The difference lies in the fact that, in case of modifications to the HTML, we have to change the code in a single point, more precisely in the second line, instead of three different spots. In fact, the name of the variable remains the same (pardon the play with words), expanding the modifications in the whole code. Can you find another element which can be saved in a variable?

But where are the effects of jQuery?

Let’s try now to render our jButton a little more interesting by adding a simple animation to the switching on/off to emulate an energy efficient lamp. (here on YIW we are very sensitive in environmental terms). The peculiar feature of this type of lamps is that they don’t reach their maximal capacity instantaneously, but require a couple of seconds as warm up. To sketch out this effect, we will use jQuery’s fadeIn function. The syntax is the following:

$("selected_item").fadeIn(duration);

The effect produced by fadeIn is the appearance as fading of a hidden item. The duration can be expressed in milliseconds, or in one of the three key words: “slow”, “normal”, “fast”. It is important to use the inverted commas when text parameters are passed to a function, while we leave them out for the numerical values.

I have highlighted the fact that the item has to be hidden so that fadeIn can operate. At the moment, however, our div “lamp” is not hidden. We can fix it by adding the line:

display:none;

to our CSS, or we can use jQuery’s hide function which, as the name suggests, hides the selected item. We combine then these notions in our JavaScript code:

$(document).ready(function() {
  var interrupter = $("a#interrupter");
  //hide the div lamp
  $("div.lamp").hide();
  interrupter.toggle(
  function() {
    //remember the concatenation?
    $("div.lamp").addClass("on").fadeIn(5000);
    interrupter.html("Turn Lamp Off");
  },
  function() {
    //"Turning off" the lamp,I hide the div
    $("div.lamp").removeClass("on").hide();
    interrupter.html("Turn Lamp On");
  });
});

With these modifications, we have hidden the div “lamp” (line 4) and then, exploiting the concatenation, we have set it up that it appears fading, with a duration of 5 seconds (5000 milliseconds). At the switching off, we hide the div again preparing thus for a new switching on.

It is important for a successful code to return to a consistent state: if we wouldn’t hide the div again, the fadeIn would function only the first time, while it would fail subsequently, because it wouldn’t have a hidden element on which to operate. This should be the final result.

Conclusions

Fiuu! We made a lot of way in this lesson: we started with a raw interrupter, to the point of obtaining a variable interrupter for an energy efficient lamp! And all this just in a few lines thanks to jQuery. In the next lesson we will deal with how to modify the CSS styles of an item without necessarily adding or removing a class and we will discover also some other standard jQuery effect. Till next week!

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:

3 comments

Trackback e pingback

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

Leave a Reply

Current month ye@r day *