Aprenderás cómo usar este lenguaje de interacción y a que ocurran cambios en la web a medida que el usuario vaya interactuando con la misma.
Si ya sabes algún lenguaje de programación, puedes leerte por encima la parte de sintaxis común de lenguajes de programación e ir directamente al apartado jQuery.
Variables
Hay muchas formas de representar la información. Se puede representar el número de estudiantes con un entero, tu nombre con un string (texto), etc. Para programar los puedes querer almacenar en algún sitio: en variables.
Una variable es una referencia donde se guarda información. Imagina que quieres guardar el hipotético número de estudiantes de una clase de Libre University, 80. Podrías hacerlo así en Javascript:
var students = 80;
Estamos creando la variable students
usando la palabra var
y le asignamos el valor de 80
. Si despu'es queremos saber el número de estudiantes para el año que viene, podríamos hacerlo así:
var students = 80;
var graduating = 20;
var joining = 30;
var nextyear = students + joining - graduating;
Tipos de variables
Algunos ejemplos explicados de cómo definir variables 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 mostrarlos, podríamos usar la función alert()
y un pop-up mostrará su valor.
Control structures
The programs normally execute from top to bottom, line by line. However there are few structures in javascript that can change this, one being control structures. The characteristic of them is that they are a single operation followed by a code block delimited by { }
, and that block is the part that gets modified.
if ( condition )
When using the variables mentioned above sometimes you want that a piece of code is executed in one situation 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 ==
instead of =
. This is because a single equal sign is used to assign a variable, while a double (or triple) equal is used to compare two things.
But what do you do when you also want to do something when the statement 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 compare any type of variable. You can also compare numbers and operations like greater than or smaller 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 ( initial ; condition ; change )
There's another important control structure called for
. It is used when you want to perform an operation many times but you don't want to write the same code over and over again. For example, say Bloody Mary 3 times:
for(var i = 0; i < 3; i++) {
alert("Bloody Mary");
}
Note how we put i < 3
to display it three times, since it will be executed when i is 0, when i is 1 and when i is 2. If we had said i <= 3
then we'd also execute the block when i is 3, so it'd be 4 times in total.
.forEach(function(){})
A similar one would be .forEach()
. It is used to loop an array, however we'll see it later since it involves method and callbacks, some more advanced techniques.
Functions
A function is a piece of code that takes an input and returns an output. Let's see a typical example, the function "sum":
function sum (a, b) {
return a + b;
}
This function accepts two arguments and return 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);
Objects and methods
An object is a type of variable that can contain other elements called properties. It is different from an array in that each element has a name. For example, you can have the object person:
var person = {
firstname: "John",
lastname: "Doe",
age: 21
};
To read or write one of the properties of person you can access 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);
Objects can also store functions. Let's allow for the previous person 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 access a variable within an object or function, you can use this
keyword. For the last example:
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 execute an action when something special happens. For example, let's say we want to execute a function after 1 second. In other languages you'd do something like this:
some actions
sleep(1000) // sleep 1000ms
actionAfter1s()
other actions
However, we wouldn't be able to execute "other actions" until after we have executed the sleep(1000). This is bad to do many things at the same time, so javascript uses async functions to do that. There are some functions defined as async that accept a function as a variable and then execute it when the condition is met. For the same example 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 screen. This is great so scripts don't block each other and many things can be executed independently.
However, you should also be careful, as if you are accesing outside variables they might have changed by the time you use them. This will display "3" three times instead of 1, 2 and 3:
for(var i = 0; i < 3; i++) {
setTimeout(function(){
alert(i);
}, 1000);
}
jQuery
Por ahora hemos visto cómo funciona javascript como lenguaje de programación. Pero este también se usa para interactuar con la web, por lo que podemos acceder al HTML directamente desde el mismo. Normalmente se usa la librería jQuery, ya que facilita mucho las cosas.
La misma usa selectores de CSS para encontrar elementos 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 interactuar con los mismos. Por ejemplo, digamos que queremos cambiar todos los párrafos por un "Hola Mundo!". Podríamos hacerlo de la siguiente forma:
var parrafos = $('p');
parrafos.html('Hola Mundo!');
O podemos simplificarlo a:
$('p').html('Hola Mundo!');
Esta propiedad se llama "chainable", que quiere decir que podemos, con un mismo selector, aplicarle varias operaciones. Ahora añadiremos una clase a todos los párrafos, a parte de cambiarles el contenido:
$('p').html('Hola Mundo!').addClass('superparagraph');
Estos métodos (funciones), html()
y addClass()
, son definidos por jQuery y puedes encontrar una lista en la Documentación Oficial, pero estos son de los más usados:
.on()
.html()
, .append()
, .prepend()
.addClass()
, .hasClass()
, .removeClass()
.attr()
Y no sólo eso, sino que algunos de estos métodos tienen varios usos. Por ejemplo, si usamos el método .html()
sin ningún parámetro nos devolverá el contenido del [primer] elemento seleccionado, mientras que si le ponemos algo dentro cambiará el html a todos los elementos seleccionados:
// 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 eventos. Uno de los métodos más usados, .on(), se usa para cuando el usuario hace algo. Como por ejemplo click. Como esto es un evento asíncrono, le pasamos una función que será la que se ejecute cuando el usuario haga click en el elemento seleccionado:
$('button').on('click', function(){
alert('Hola Mundo!');
});
Haciendo Like
Esto resulta muy útil cuando, por ejemplo, queremos cambiar algo cuando el usuario le da click a Like. Para esto, nos definiremos el siguiente HTML:
<button data-id="25">Like</button>
Con el siguiente estilo en CSS:
button {
color: #000000; /* negro */
background: #ffffff; /* blanco */
}
.liked {
color: #ffffff; /* blanco */
background: #ff0000; /* rojo */
}
Y el siguiente 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 resultado en jsfiddle.
AJAX, llamadas al servidor
Pero si nos fijamos, si hacemos "Like" y refrescamos la página el estado se habrá borrado. Esto es porque el servidor no sabe qué estamos cambiando, sólo lo sabe nuestro navegador. Para enviarle esta información al servidor usaremos AJAX (Asynchronous 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 embargo, si lo probamos no funcionará ya que la url /like no existe ahora mismo. Es importante que veamos cómo enviar las peticiones, pero cómo y dónde recibirlas lo veremos en el siguiente capítulo.