History: Javascript

Revision made 8 years ago by Francisco Presencia. Go to the last revision.

Ap­renderás cómo usar este len­guaje de in­terac­ción y a que oc­ur­ran cam­bios en la web a medida que el usuario vaya in­terac­tuan­do con la misma.

Si ya sabes algún len­guaje de pro­gramación, puedes leer­te por en­cima la parte de sin­taxis común de len­guajes de pro­gramación e ir di­rec­tamen­te al apar­tado jQue­ry.

Vari­ables

Hay muc­has for­mas de re­presen­tar la in­for­mación. Se puede re­presen­tar el número de es­tudian­tes con un en­tero, tu nombre con un str­ing (texto), etc. Para pro­gramar los puedes quer­er al­macenar en algún sitio: en vari­ables.

Una vari­able es una re­feren­cia donde se guar­da in­for­mación. Im­agina que quieres guar­dar el hipotético número de es­tudian­tes de una clase de Libre Uni­vers­ity, 80. Podrías hacer­lo así en Javascript:

var students = 80;

Es­tamos crean­do la vari­able students usan­do la palab­ra var y le as­ig­namos el valor de 80. Si despu'es queremos saber el número de es­tudian­tes para el año que viene, podríamos hacer­lo así:

var students = 80;
var graduating = 20;
var joining = 30;
var nextyear = students + joining - graduating;

Tipos de vari­ables

Al­gunos ejemplos ex­plicados de cómo de­finir vari­ables en Javascript:

// Number:
var years = 24;

// Boolean:
var married = true;

// String:
var address = "Street 24, New York";

// Array (of strings):
var friends = ["Mary", "John", "July"];

// Object
var friend = { firstname: "Peter", lastname: "Smith" };

Para mostrar­los, podríamos usar la función alert() y un pop-up mostrará su valor.

Con­trol struc­tures

The pro­grams nor­mal­ly ex­ecute from top to bot­tom, line by line. Howev­er there are few struc­tures in javascript that can chan­ge this, one being con­trol struc­tures. The charac­teris­tic of them is that they are a single op­era­tion fol­lowed by a code block de­limited by { }, and that block is the part that gets modified.

if ( con­di­tion )

When using the vari­ables men­tioned above some­times you want that a piece of code is ex­ecuted in one situa­tion or not. For doing this we use the if clause:

var name = "John";

if (name == "Peter") {
  alert("Hello Peter");
}

if (name == "John") {
  alert("Hello John");
}

Notice how we use == in­stead of =. This is be­cause a single equal sign is used to as­sign a vari­able, while a doub­le (or tri­ple) equal is used to com­pare two th­ings.

But what do you do when you also want to do some­th­ing when the state­ment is not true? Then you can use the else clause:

var name = "Peter";
if (name == "Peter") {
  alert("Hello Peter");
}
else {
  alert("You are not Peter!");
}

We can com­pare any type of vari­able. You can also com­pare numb­ers and op­era­tions like great­er than or small­er than like this:

var age = 17;
if (age >= 18) {
  alert("You are allowed to see this page");
}
else {
  alert("This page is only for adults");
}

for ( in­iti­al ; con­di­tion ; chan­ge )

There's an­oth­er im­por­tant con­trol struc­ture cal­led for. It is used when you want to per­form an op­era­tion many times but you don't want to write the same code over and over again. For ex­am­ple, say Bloody Mary 3 times:

for(var i = 0; i < 3; i++) {
  alert("Bloody Mary");
}

Note how we put i < 3 to dis­play it three times, since it will be ex­ecuted when i is 0, when i is 1 and when i is 2. If we had said i <= 3 then we'd also ex­ecute the block when i is 3, so it'd be 4 times in total.

.forEach(func­tion(){})

A similar one would be .forEach(). It is used to loop an array, howev­er we'll see it later since it in­vol­ves met­hod and callbacks, some more ad­vanced tech­niques.

$$\sum i c = \pm\sqrt{a^2 + b^2}$$

Func­tions

A func­tion is a piece of code that takes an input and re­turns an out­put. Let's see a typ­ical ex­am­ple, the func­tion "sum":

function sum (a, b) {
  return a + b;
}

This func­tion ac­cepts two ar­gu­ments and re­turn the sum of them. To use it you can test this code:

function sum (a, b) {
  return a + b;
}
var result = sum(5, 7);
alert(result);

Ob­jects and met­hods

An ob­ject is a type of vari­able that can con­tain other ele­ments cal­led pro­pert­ies. It is dif­ferent from an array in that each ele­ment has a name. For ex­am­ple, you can have the ob­ject per­son:

var person = {
  firstname: "John",
  lastname: "Doe",
  age: 21
};

To read or write one of the pro­pert­ies of per­son you can ac­cess them using a .:

var person = {
  firstname: "Jonh"
};

// Oops, we made a typo in firstname. Fix it:
person.firstname = "John";

// Display the name of the person
alert(person.firstname);

Ob­jects can also store func­tions. Let's allow for the pre­vi­ous per­son to say his name:

var person = {
  firstname: "John",
  sayHi: function(){
    alert("Hi, I'm John");
  }
};

// It shows "Hi, I'm John"
person.sayHi();

this

To ac­cess a vari­able with­in an ob­ject or func­tion, you can use this keyword. For the last ex­am­ple:

var person = {
  firstname: "John",
  sayHiTo: function(to){
    var name = this.firstname;

    // Join the string with the name
    alert("Hi " + to + ", I'm " + name);
  }
};

// It shows "Hi Peter, I'm John"
person.sayHiTo("Peter");

Async

There are some times that we want to ex­ecute an ac­tion when some­th­ing speci­al hap­pens. For ex­am­ple, let's say we want to ex­ecute a func­tion after 1 second. In other lan­guages you'd do some­th­ing like this:

some actions
sleep(1000) // sleep 1000ms
actionAfter1s()
other actions

Howev­er, we would­n't be able to ex­ecute "other ac­tions" until after we have ex­ecuted the sleep(1000). This is bad to do many th­ings at the same time, so javascript uses async func­tions to do that. There are some func­tions de­fined as async that ac­cept a func­tion as a vari­able and then ex­ecute it when the con­di­tion is met. For the same ex­am­ple as above, we would do this in javascript:

alert(1);

function actionAfter1s(){
  alert(3);
};

// Async function, 'setTimeout'
setTimeout(actionAfter1s, 1000);

alert(2);

In this way, we would see "1", "2" and then "3" after 1 second in that order on the scre­en. This is great so scripts don't block each other and many th­ings can be ex­ecuted in­depen­dent­ly.

Howev­er, you should also be care­ful, as if you are ac­ces­ing out­side vari­ables they might have chan­ged by the time you use them. This will dis­play "3" three times in­stead of 1, 2 and 3:

for(var i = 0; i < 3; i++) {
  setTimeout(function(){
    alert(i);
  }, 1000);
}

jQue­ry

Por ahora hemos visto cómo func­iona javascript como len­guaje de pro­gramación. Pero este también se usa para in­terac­tuar con la web, por lo que podemos ac­ced­er al HTML di­rec­tamen­te desde el mismo. Nor­malmen­te se usa la li­brería jQue­ry, ya que facilita mucho las cosas.

La misma usa selec­tores de CSS para en­contrar elemen­tos en el html.

// Encuentra todos los parrafos en la web
var parrafos = $('p');

// Encuentra todos los elementos con la clase "button" (usamos ".")
var botones = $('.button');

Tras esto, podemos in­terac­tuar con los mis­mos. Por ejemplo, di­gamos que queremos cam­biar todos los pár­rafos por un "Hola Mundo!". Podríamos hacer­lo de la siguien­te forma:

var parrafos = $('p');
parrafos.html('Hola Mundo!');

O podemos simplificar­lo a:

$('p').html('Hola Mundo!');

Esta pro­piedad se llama "chain­able", que quiere decir que podemos, con un mismo selec­tor, ap­licar­le varias op­eraciones. Ahora añadiremos una clase a todos los pár­rafos, a parte de cam­biar­les el con­tenido:

$('p').html('Hola Mundo!').addClass('superparagraph');

Estos métodos (func­iones), html() y addClass(), son de­finidos por jQue­ry y puedes en­contrar una lista en la Documen­tación Of­ici­al, pero estos son de los más usados:

.on()

.html(), .append(), .prepend()

.addClass(), .hasClass(), .removeClass()

.attr()

Y no sólo eso, sino que al­gunos de estos métodos tien­en varios usos. Por ejemplo, si usamos el método .html() sin ningún parámetro nos de­volv­erá el con­tenido del [prim­er] elemen­to selec­cionado, mientras que si le ponemos algo de­ntro cam­biará el html a todos los elemen­tos selec­cionados:

// Recupera el texto del primer párrafo
var texto = $('p').html();

// Cambia el texto de todos los párrafos
$('p').html('Hola mundo!');

También podemos hacer uso de even­tos. Uno de los métodos más usados, .on(), se usa para cuan­do el usuario hace algo. Como por ejemplo click. Como esto es un even­to as­íncrono, le pasamos una función que será la que se ejecute cuan­do el usuario haga click en el elemen­to selec­cionado:

$('button').on('click', function(){
  alert('Hola Mundo!');
});

Hacien­do Like

Esto re­sul­ta muy útil cuan­do, por ejemplo, queremos cam­biar algo cuan­do el usuario le da click a Like. Para esto, nos de­finiremos el siguien­te HTML:

<button data-id="25">Like</button>

Con el siguien­te es­tilo en CSS:

button {
  color: #000000; /* negro */
  background: #ffffff; /* blanco */
}

.liked {
  color: #ffffff; /* blanco */
  background: #ff0000; /* rojo */
}

Y el siguien­te javascript:

// Cuando el usuario hace click en un elemento button
$('button').on('click', function(){

  // Le toggleamos (añadir/quitar) la clase "liked"
  // this es el elemento sobre el que has hecho click
  $(this).toggleClass('liked');
});

Puedes ver el re­sul­tado en jsfiddle.

AJAX, llamadas al ser­vidor

Pero si nos fijamos, si hacemos "Like" y re­fres­camos la página el es­tado se habrá bor­rado. Esto es por­que el ser­vidor no sabe qué es­tamos cam­bian­do, sólo lo sabe nuestro navegador. Para en­viar­le esta in­for­mación al ser­vidor usaremos AJAX (As­ynchron­ous JavaScript and XML):

// Cuando el usuario hace click en un elemento button
$('button').on('click', function(){

  // Le toggleamos (añadir/quitar) la clase "liked"
  // "this" es el elemento sobre el que has hecho click
  $(this).toggleClass('liked');

  // Recuperamos el id del elemento
  var id = $(this).data('id');

  // Vemos si le hemos dado a like o lo hemos cancelado (true/false)
  var isLiked = $(this).hasClass('liked');

  var url = '/like';
  var data = { id: id, like: isLiked };
  var done = function(){
    alert('Hecho!');
  }

  // Enviamos la petición al servidor
  $.post(url, data, done);
});

Sin em­bar­go, si lo pro­bamos no func­ionará ya que la url /like no ex­is­te ahora mismo. Es im­por­tante que veamos cómo en­viar las peticiones, pero cómo y dónde re­cibir­las lo veremos en el siguien­te capítulo.