spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I...
Transcript of spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I...
![Page 1: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/1.jpg)
Introduccion a JavaScript
Jesus Arias Fisteus
Computacion Web (2019/20)
Computacion Web (2019/20) Introduccion a JavaScript 1
![Page 2: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/2.jpg)
Parte I
El lenguaje de programacion JavaScript
Computacion Web (2019/20) Introduccion a JavaScript 2
![Page 3: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/3.jpg)
Introduccion a JavaScript
I JavaScript:I Lenguaje de programacion interpretado.I Debilmente tipado.I Orientado a objetos.I De proposito general, pero utilizado habitualmente en
navegadores Web (client-side JavaScript).I Estandarizado bajo el nombre de ECMAScript.
Computacion Web (2019/20) Introduccion a JavaScript 3
![Page 4: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/4.jpg)
Sentencias de control
I Relativamente similares en sintaxis a las de Java y C:I if, switch.I for, while, do while.I return, break, continue.
Computacion Web (2019/20) Introduccion a JavaScript 4
![Page 5: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/5.jpg)
Condicionales y comparaciones
I Operadores de comparacion:I ===, !==I <, <=, >, >=
I Operadores logicos:I &&, ||, !
1 if (n === 1) {2 console.log("You have 1 new message.");3 } else {4 console.log("You have " + n + " new messages.");5 }
Computacion Web (2019/20) Introduccion a JavaScript 5
![Page 6: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/6.jpg)
Bucles
1 var count = 0;2 while (count < 10) {3 console.log(count);4 count ++;5 }6
7 for(var count = 0; count < 10; count ++) {8 console.log(count);9 }
10
11 var person = {fname: "John", lname: "Doe", age: 25};12 var x;13 for (x in person) {14 console.log(person[x]);15 }
Computacion Web (2019/20) Introduccion a JavaScript 6
![Page 7: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/7.jpg)
Tipos de datos
I Tipos de datos simples:I Numeros, cadenas de texto, booleanos, null, undefined.
I Objetos:I Arrays, funciones, expresiones regulares, objetos.
Computacion Web (2019/20) Introduccion a JavaScript 7
![Page 8: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/8.jpg)
Objetos
I Contenedores de propiedades:I Cada propiedad tiene un nombre y un valor.I Un objeto puede heredar de otro objeto.I No existe un concepto de clase que restrinja las propiedades
que puede tener un objetoI Aunque ECMAScript 6 (2015) introduce una capa sintactica
que permite definir clases.
Computacion Web (2019/20) Introduccion a JavaScript 8
![Page 9: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/9.jpg)
Ejemplo: Inicializacion literal de objetos
1 var empty_object = {};2
3 var stooge = {4 "first -name": "Jerome",5 "last -name": "Howard"6 };
Computacion Web (2019/20) Introduccion a JavaScript 9
![Page 10: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/10.jpg)
Ejemplo: Inicializacion literal de objetos
1 var flight = {2 airline: "Oceanic",3 number: 815,4 departure: {5 IATA: "SYD",6 time: "2004 -09 -22 14:55",7 city: "Sydney"8 },9 arrival: {
10 IATA: "LAX",11 time: "2004 -09 -23 10:42",12 city: "Los Angeles"13 }14 };
Computacion Web (2019/20) Introduccion a JavaScript 10
![Page 11: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/11.jpg)
Acceso a propiedades de objetos
I Mediante corchetes o con punto:
1 stooge["first -name"] // "Jerome"2 flight.departure.IATA // "SYD"
I Las propiedades que no existen devuelven undefined:
1 stooge["middle -name"] // undefined2 flight.status // undefined3 stooge["FIRST -NAME"] // undefined
Computacion Web (2019/20) Introduccion a JavaScript 11
![Page 12: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/12.jpg)
Actualizacion de propiedades
I Mediante asignacion:
1 stooge['first -name'] = 'Jerome ';2 flight.number = 7005;
I Si la propiedad no existe en el objeto, se creaautomaticamente:
1 stooge['middle -name'] = 'Lester ';2 stooge.nickname = 'Curly';3 flight.equipment = {4 model: 'Boeing 777'5 };6 flight.status = 'overdue ';
Computacion Web (2019/20) Introduccion a JavaScript 12
![Page 13: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/13.jpg)
Objetos por referencia
I Los objetos se pasan por referencia, al igual que en Java:1 var x = stooge;2 x.nickname = 'Curly ';3 var nick = stooge.nickname;4 // nick is 'Curly ' because x and stooge5 // are references to the same object6
7 var a = {}, b = {}, c = {};8 // a, b, and c each refer to a9 // different empty object
10 a = b = c = {};11 // a, b, and c all refer to12 // the same empty object
Computacion Web (2019/20) Introduccion a JavaScript 13
![Page 14: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/14.jpg)
Funciones
I Las funciones son objetos:I Pueden usarse como cualquier otro objeto en asignaciones, etc.
I Declaracion literal de funciones:1 // Create a variable called add and store a2 // function in it that adds two numbers.3
4 var add = function(a, b) {5 return a + b;6 };
Computacion Web (2019/20) Introduccion a JavaScript 14
![Page 15: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/15.jpg)
Invocacion a funciones
I Varios patrones de invocacion:I Invocacion como funcion.I Invocacion como metodo.I Invocacion como constructor.I Invocacion mediante apply.
Computacion Web (2019/20) Introduccion a JavaScript 15
![Page 16: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/16.jpg)
Invocacion como funcion
1 var add = function(a, b) {2 return a + b;3 };4
5 var sum = add(3, 4); // sum is 7
Computacion Web (2019/20) Introduccion a JavaScript 16
![Page 17: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/17.jpg)
Invocacion como metodo
1 var myObject = {2 value: 0,3 increment: function(inc) {4 this.value += inc;5 }6 };7
8 myObject.increment (2);9 myObject.value; // 2
10
11 myObject.increment (1);12 myObject.value; // 3
Computacion Web (2019/20) Introduccion a JavaScript 17
![Page 18: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/18.jpg)
Invocacion como constructor
1 // Declare the constructor function2 var Color = function(r, g, b) {3 // Attributes4 this.r = r;5 this.g = g;6 this.b = b;7
8 // Methods9 this.luminosity = function () {
10 return Math.round (0.21 * this.r + 0.72 * this.g11 + 0.07 * this.b);12 }13
14 this.toGrayScale () {15 var a = this.luminosity ();16 return new Color(a, a, a);17 }18 }19
20 // Create a new object21 var red = new Color (255, 0, 0);22 red.luminosity (); // 5423 var gray = red.toGrayScale (); // Color (r: 54, g: 54, b: 54)
Computacion Web (2019/20) Introduccion a JavaScript 18
![Page 19: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/19.jpg)
Clases (a partir de ECMAScript 6)
1 class Color {2 constructor(r, g, b) {3 this.r = r;4 this.g = g;5 this.b = b;6 }7
8 get luminosity () {9 return Math.round (0.21 * this.r + 0.72 * this.g
10 + 0.07 * this.b);11 }12
13 toGrayScale () {14 var a = this.luminosity;15 return new Color(a, a, a);16 }17 }18
19 // Create a new object20 var red = new Color (255, 0, 0);21 red.luminosity; // 5422 var gray = red.toGrayScale (); // Color (r: 54, g: 54, b: 54)
Computacion Web (2019/20) Introduccion a JavaScript 19
![Page 20: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/20.jpg)
Excepciones
1 var add = function (a, b) {2 if (typeof a !== 'number ' || typeof b !== 'number ') {3 throw {4 name: 'TypeError ',5 message: 'add needs numbers '6 };7 }8 return a + b;9 }
10
11 try {12 add("seven");13 } catch (e) {14 document.writeln(e.name + ': ' + e.message);15 }
Computacion Web (2019/20) Introduccion a JavaScript 20
![Page 21: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/21.jpg)
Arrays
1 var empty = [];2 var numbers = [3 'zero', 'one', 'two', 'three ', 'four',4 'five', 'six', 'seven ', 'eight ', 'nine'5 ];67 empty [1] // undefined8 numbers [1] // 'one'9
10 empty.length // 011 numbers.length // 101213 numbers.length = 3;14 // numbers is ['zero ', 'one ', 'two ']1516 numbers[numbers.length] = 'shi';17 // numbers is ['zero ', 'one ', 'two ', 'shi ']1819 numbers.push('go');20 // numbers is ['zero ', 'one ', 'two ', 'shi ', 'go ']2122 delete numbers [2];23 // numbers is ['zero ', 'one ', undefined , 'shi ', 'go ']2425 numbers.splice(2, 1);26 // numbers is ['zero ', 'one ', 'shi ', 'go ']
Computacion Web (2019/20) Introduccion a JavaScript 21
![Page 22: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/22.jpg)
Client-side JavaScript
I El termino client-side JavaScript hace referencia al entorno deejecucion de codigo JavaScript proporcionado por losnavegadores web.
I Este entorno lo conforman las APIs de JavaScript definidaspor HTML5 y otros estandares relacionados, e implementadaspor los navegadores.
Computacion Web (2019/20) Introduccion a JavaScript 22
![Page 23: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/23.jpg)
Client-side JavaScript
I Client-side JavaScript hace interactivo el documento HTMLmediante, principalmente:
I Manejadores de eventos:I Se puede ejecutar codigo especıfico (manejadores) cuando se
cargue/cierre la pagina, el usuario interaccione con elementosde la misma, o periodicamente.
I Modificacion dinamica del documento:I Mediante APIs (p.e. la API de DOM) el programa JavaScript
puede modificar el documento HTML que se visualiza.
Computacion Web (2019/20) Introduccion a JavaScript 23
![Page 24: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/24.jpg)
Inclusion de JavaScript en HTML
1 <!-- directamente con el elemento script2 (en la cabecera o en el cuerpo del documento) -->3 <script type="text/javascript">4 var d = new Date();5 document.write(d.toLocaleString ());6 </script >78 <!-- desde un recurso externo -->9 <script src="scripts/util.js" type="text/javascript"></script >
1011 <!-- desde un manejador de eventos de HTML -->12 <input type="button" value="Change" onclick="changeName ()">13 <p onmouseover="showHelp('p1 ')">...</p>
Computacion Web (2019/20) Introduccion a JavaScript 24
![Page 25: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/25.jpg)
Referencias
I Douglas Crockford. “JavaScript: The Good Parts”. O’ReillyMedia, Inc. (2008)
I Acceso en lınea en SafariI La mayorıa de los ejemplos de estas transparencias provienen
de este libro.
I David Flanagan. “JavaScript: The Definitive Guide” (6th Ed.)O’Reilly.
I Acceso en lınea en Safari
Computacion Web (2019/20) Introduccion a JavaScript 25
![Page 26: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/26.jpg)
Parte II
JQuery
Computacion Web (2019/20) Introduccion a JavaScript 26
![Page 27: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/27.jpg)
JQuery
I Biblioteca de codigo para JavaScript:I Proporciona una API mas sencilla para el programador:
I Acceso al arbol DOM, envıo de peticiones XMLHttpRequest,animaciones, etc.
I Proporciona un acceso uniforme a su funcionalidad, incluso enversiones antiguas de navegadores.
Computacion Web (2019/20) Introduccion a JavaScript 27
![Page 28: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/28.jpg)
Hola mundo con JQuery
1 <!DOCTYPE html>2 <html>3 <head>4 <meta charset="UTF -8">5 <title>Mi primera pagina con jQuery </title>6 <script src="https :// ajax.googleapis.com/ajax/libs/
jquery /3.2.1/ jquery.min.js"></script >7 <script type="text/javascript">8 $(document).ready(function () {9 console.log("ready!");
10 });11 </script >12 </head>13 <body>14 <p>¡Hola Mundo!</p>15 </body>16 </html>
Computacion Web (2019/20) Introduccion a JavaScript 28
![Page 29: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/29.jpg)
El evento ready
1 // Se ejecuta el codigo de inicializaci on cuando el arbol2 // est e cargado3 $(document).ready(function () {4 console.log("ready!");5 });6
7 // Forma compacta equivalente a lo anterior8 $(function () {9 console.log("ready!");
10 });
Computacion Web (2019/20) Introduccion a JavaScript 29
![Page 30: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/30.jpg)
Encadenamiento de metodos
I Version “tradicional”:
1 var title = $("<h1>¡Hola!</h1>");2 title.css("font -family", "sans -serif");3 var body = $("body");4 body.prepend(title);5 body.css("color", "navy");6 body.fadeIn (5000);7 body.fadeOut (5000);
I Version con encadenamiento de metodos:
1 var title = $("<h1>¡Hola!</h1>").css("font -family",2 "sans -serif");3 $("body").prepend(title)4 .css("color", "navy")5 .fadeIn (5000)6 .fadeOut (5000);
Computacion Web (2019/20) Introduccion a JavaScript 30
![Page 31: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/31.jpg)
Acceso a atributos de elementos
1 // Consulta atributo title del primer pa rrafo2 $("p").attr("title");3
4 // Establece el atributo src del elemento con id "logo"5 $("#logo").attr("src", "logo.png");6
7 // Establece varios atributos a la vez8 $("#banner").attr({src:"banner.gif",9 alt:"Advertisement",
10 width :720,11 height :64});
Computacion Web (2019/20) Introduccion a JavaScript 31
![Page 32: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/32.jpg)
Acceso a atributos de elementos
1 // Todos los enlaces se cargar an en ventana nueva2 $("a").attr("target", "_blank");3
4 // Los enlaces se cargar an en ventana nueva o en la actual5 // dependiendo de si referencian a otro dominio o al actual6 $("a").attr("target", function () {7 if (this.host == location.host) {8 return "_self";9 } else {
10 return "_blank";11 }12 });13
14 // Elimina el atributo target de todos los enlaces15 $("a").removeAttr("target");
Computacion Web (2019/20) Introduccion a JavaScript 32
![Page 33: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/33.jpg)
Acceso a propiedades CSS de elementos
1 // Lee el valor de font -weight en el primer elemento h12 $("h1").css("font -weight");3
4 // establece una propiedad en todos los h15 $("h1").css("font -variant", "small -caps");6
7 // establece una propiedad compuesta8 $("div.note").css("border", "solid black 2px");9
10 // establece varias propiedades a la vez11 $("h1").css({ backgroundColor: "black",12 textColor: "white",13 fontVariant: "small -caps",14 padding: "10px 2px 4px 20px",15 border: "dotted black 4px"});16
17 // Incrementa los tama~nos de tipograf ıa un 25 %18 $("h1").css("font -size", function(i, curval) {19 return Math.round (1.25 * parseInt(curval));20 });
Computacion Web (2019/20) Introduccion a JavaScript 33
![Page 34: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/34.jpg)
Acceso al atributo class
1 // A~nade la clase "firstpara" a los p2 // que aparezcan a continuaci on de un h13 $("h1+p").addClass("firstpara");4
5 // Elimina una clase de todos los pa rrafos6 $("p").removeClass("firstpara");7
8 // Elimina todas las clases9 $("p").removeClass ();
10
11 // Alterna la clase (con dos clases a la vez)12 $("h1").toggleClass("big bold");13
14 // Averigua si un elemento es de las clases big y bold15 $("#first").is(".big.bold");
Computacion Web (2019/20) Introduccion a JavaScript 34
![Page 35: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/35.jpg)
Acceso a valores de controles en formularios
1 // Obtiene el valor del control con id "surname"2 $("#surname").val()3
4 // Obtiene el valor del bot on radio que est e seleccionado5 $("input:radio[name=ship]: checked").val()6
7 // Establece el valor de un control8 $("#total_price").val("23.99")9
10 // Marca dos checkboxes dados sus nombres o valores11 $("input:checkbox").val(["opt1", "opt2"])12
13 // Restablece los valores por defecto14 $("input:text").val(function () {15 return this.defaultValue;16 })
Computacion Web (2019/20) Introduccion a JavaScript 35
![Page 36: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/36.jpg)
Acceso al contenido de un elemento
1 // Obtiene el tıtulo del documento2 var t = $("head title").text();3
4 // Obtiene el contenido del primer h1 como texto HTML5 var hdr = $("h1").html()6
7 // Establece un texto8 $("#title").text("Another title")9
10 // Numera las secciones h2 del documento11 $("h2").text(function(n, current) {12 return " " + (n+1) + ": " + current;13 });
Computacion Web (2019/20) Introduccion a JavaScript 36
![Page 37: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/37.jpg)
Arbol DOM
1 <!DOCTYPE html>2 <html>3 <head>4 <title>Barney says ...</title>5 </head>6 <body>7 <h1>Barney says</h1>8 <p>9 This is going to be <em>legendary </em>
10 </p>11 </body>12 </html>
Computacion Web (2019/20) Introduccion a JavaScript 37
![Page 38: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/38.jpg)
Arbol DOM
html
head body
title
"Barney says..."
h1
"Barney says" em"This is going to be"
"legendary"
p
Computacion Web (2019/20) Introduccion a JavaScript 38
![Page 39: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/39.jpg)
Modificaciones del documento
1 // A~nade al final del contenido de un elemento2 $("#log").append("<em>new content </em >");3
4 // A~nade al principio del contenido de cada h15 $("h1").prepend("Chapter: ");6
7 // A~nade inmediatamente antes o despu es de cada h18 $("h1").before("<hr>");9 $("h1").after("<hr >");
10
11 // Reemplaza cada h2 por un h1 , conservando el contenido12 $("h2").each(function () {13 var h2 = $(this);14 h2.replaceWith("<h1>" + h2.html() + " </h1>");15 });16
17 // Envuelve cada imagen en un elemento div18 $("img").wrap("<div class='image '></div >");19
20 // Envuelve el contenido de cada elemento div21 // con clase "img" con otro div22 $("div.image").wrapInner("<div class='inner '></div >");
Computacion Web (2019/20) Introduccion a JavaScript 39
![Page 40: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/40.jpg)
Modificaciones del documento
1 // Hay variantes de algunas de las funciones anteriores2 // que aplican sobre el contenido a insertar3 $("<em>new content </em>").appendTo("#log");4 $(document.createTextNode("Chapter: ")).prependTo("h1");5 $("<hr/>").insertBefore("h1");6 $("<hr/>").insertAfter("h1");
Computacion Web (2019/20) Introduccion a JavaScript 40
![Page 41: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/41.jpg)
Copia de elementos
1 // A~nade una secci on nav2 $(document.body)3 .append("<nav id='linklist '><h1>Links </h1 ></nav >");4
5 // Copia todos los enlaces6 $("a").clone().appendTo("#linklist");7
8 // Lınea nueva tras cada enlace9 $("#linklist > a").after("<br/>");
Computacion Web (2019/20) Introduccion a JavaScript 41
![Page 42: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/42.jpg)
Eliminacion de contenido
1 // Elimina el contenido del elemento con id "log",2 // pero mantiene el propio elemento3 $("#log").empty ();4
5 // Elimina el elemento con id "log", includidos6 // los manejadores de eventos y datos auxiliares7 $("#log").remove ();8
9 // Extrae el elemento con id "log" y su contenido ,10 // pero conserva manejadores de eventos y datos auxiliares.11 // Es util para volver a insertar el elemento mas tarde.12 var e = $("#log").detach ();13
14 // Elimina el elemento que envuelva al elemento con id "log"15 $("#log").unwrap ();
Computacion Web (2019/20) Introduccion a JavaScript 42
![Page 43: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/43.jpg)
Manejadores de eventos
I Permiten registrar acciones a llevar a cabo cuando ocurrandeterminados eventos sobre un elemento de la pagina:
I Se hace click sobre el elemento.I El raton pasa por encima de un elemento.I Cambia el valor de un control de un formulario.I . . .
I Las acciones se expresan como una funcion JavaScript.
Computacion Web (2019/20) Introduccion a JavaScript 43
![Page 44: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/44.jpg)
Eventos de carga del documento
I Normalmente los scripts necesitan que el documento haya sidocargado para ejecutarse de forma fiable.
I El codigo de inicializacion debe esperar a eventos que ası loindiquen.
Funcion jQuery Descripcion del evento
ready() Se ha cargado el modelo DOM del documento (se suelen registrar las inicializacionesen este evento).
.on("load", handler) Se ha representado la pagina y cargado todos sus recursos adicionales.
.on("unload", handler) Se abandona la pagina (se sigue enlace, se cierra la pestana, se recarga el documento,se va hacia atras o hacia delante).
Computacion Web (2019/20) Introduccion a JavaScript 44
![Page 45: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/45.jpg)
Eventos de carga del documento
1 // Con ready:2 $(document).ready(function () {3 console.log("ready!");4 });5
6 // Equivalente a lo anterior:7 $(function () {8 console.log("ready!");9 });
10
11 // Con load:12 $(window).on("load", function () {13 ...14 });15
16 // Cuando se abandona la pagina (se sigue enlace , se cierra17 // la pesta~na, se recarga el documento , se va hacia atr as18 // o hacia delante):19 $(window).on("unload", function () {20 ...21 });
Computacion Web (2019/20) Introduccion a JavaScript 45
![Page 46: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/46.jpg)
Eventos del navegador
Funcion jQuery Descripcion del evento
.on("error", handler) Se ha producido un error en la carga del elemento (p.e. una imagen).resize() Se envıa a window cuando cambia el tamano de la ventana.scroll() Se hace scroll en la ventana o en un elemento con barras de scroll.
Computacion Web (2019/20) Introduccion a JavaScript 46
![Page 47: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/47.jpg)
Eventos del navegador
1 $("#myphoto").on("error", function () {2 alert("Handler for .error () called.");3 });4
5 $(window).on("load", function () {6 $("#log").append("<div >Handler for window load </div >");7 });8
9 $(window).on("unload", function () {10 $("#log").append("<div >Handler for window unload </div >")
;11 });12
13 $(window).resize(function () {14 $("#log").append("<div >Handler for .resize () </div >");15 });16
17 $(window).scroll(function () {18 $("#log").append("<div >Handler for .scroll () </div >");19 });20
21 $("#target").scroll(function () {22 $("#log").append("<div >Handler for .scroll () </div >");23 });
Computacion Web (2019/20) Introduccion a JavaScript 47
![Page 48: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/48.jpg)
Eventos de formulario
Funcion jQuery Descripcion del evento
focus() El elemento consigue el foco.blur() El elemento pierde el foco.focusin() El elemento o algun descendiente suyo consigue el foco.focusout() El elemento o algun descendiente suyo pierde el foco.change() Cambia el valor del elemento (solo en controles de formulario).submit() El usuario intenta enviar el formulario.
Computacion Web (2019/20) Introduccion a JavaScript 48
![Page 49: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/49.jpg)
Eventos de formulario
1 // Si el id del elemento form es "target ":2 $("#target").submit(function(event) {3 alert("Handler for .submit () called.");4 event.preventDefault (); // evita el env ıo5 });6
7 // Fuerza el env ıo cuando se hace click en otro elemento:8 $("#other").click(function () {9 $("#target").submit ();
10 });11
12 // Cambia el valor de un control de la clase "target ":13 $(".target").change(function () {14 alert("Handler for .change () called.");15 });
Computacion Web (2019/20) Introduccion a JavaScript 49
![Page 50: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/50.jpg)
Eventos de raton
Funcion jQuery Descripcion del evento
click() El usuario hace click sobre el elemento.dblclick() El usuario hace doble click sobre el elemento.mouseenter() El puntero entra en el area del elemento.mouseleave() El puntero sale del area del elemento.hover() El puntero entra en el area del elemento (primer manejador) o sale (segundo maneja-
dor).mousedown() El boton del raton es presionado con el puntero dentro del elemento.mousemove() El puntero se mueve estando dentro del elemento.toggle() Registra dos o mas manejadores para ser ejecutados alternativamente cuando se hace
click en el elemento.
Computacion Web (2019/20) Introduccion a JavaScript 50
![Page 51: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/51.jpg)
Eventos de raton
1 $( "#target" ).dblclick(function () {2 alert( "Handler for .dblclick () called." );3 });4
5 $("#outer").mouseenter(function () {6 $("#log").append("<div >Handler for .mouseenter ().</div >");7 });8
9 $("td").hover(10 function () {11 $(this).addClass("hover");12 }, function () {13 $(this).removeClass("hover");14 }15 );
Computacion Web (2019/20) Introduccion a JavaScript 51
![Page 52: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/52.jpg)
Objetos evento
I Los manejadores de eventos reciben como argumento unobjeto que representa el evento:
I Contiene propiedades con informacion acerca del evento:I Elemento que genera el evento, teclas presionadas, posicion
del puntero, etc.
I Proporciona metodos:I Para evitar la accion por defecto (envıo de formulario, que se
cargue el destino de un enlace, etc.)I Para evitar que el evento continue propagandose o se ejecuten
otros manejadores.
Computacion Web (2019/20) Introduccion a JavaScript 52
![Page 53: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/53.jpg)
Objetos evento
1 $(function () {2 $("body").click(function(event) {3 $("#log").html("clicked: " + event.target.nodeName4 + " at " + event.screenX5 + ", " + event.screenY);6 });7 });
Computacion Web (2019/20) Introduccion a JavaScript 53
![Page 54: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/54.jpg)
Efectos predefinidos
Funcion jQuery Descripcion del efecto
fadeIn() El elemento aparece mediante cambio progresivo de opacidad.fadeOut() El elemento desaparece mediante cambio progresivo de opacidad.fadeTo() Cambia progresivamente la opacidad del elemento desde la actual hasta la final pro-
porcionada como parametro.show() Aumenta el ancho, alto y opacidad del elemento progresivamente hasta que es visible.hide() Reduce el ancho, alto y opacidad del elemento progresivamente hasta que no es visible.toggle() Alterna entre show() y hide().slideDown() Aumenta progresivamente la altura del elemento hasta que es completamente visible.slideUp() Reduce progresivamente la altura del elemento hasta que no es visible.slideToggle() Alterna entre slideDown() y slideUp().
Computacion Web (2019/20) Introduccion a JavaScript 54
![Page 55: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/55.jpg)
Efectos predefinidos
1 $(function () {2 $(".clickable").css("cursor", "pointer")3 .click(function(event) {4 $(event.target).parent ().next().toggle("slow");5 });6 });
1 $(function () {2 $(".clickable").css("cursor", "pointer")3 .click(function(event) {4 $(event.target).parent ().next()5 .slideToggle (200);6 });7 });
Computacion Web (2019/20) Introduccion a JavaScript 55
![Page 56: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/56.jpg)
Animaciones a medida
1 $(function () {2 $(".clickable").css("cursor", "pointer")3 .click(function(event) {4 $(event.target).parent ().next().animate ({5 width: "70 %",6 fontSize: "16pt"7 }, {8 duration: 10009 });
10 });11 });
Computacion Web (2019/20) Introduccion a JavaScript 56
![Page 57: spanish - UC3M · Computaci on Web (2019/20) Introduccion a JavaScript 21. Client-side JavaScript I El t ermino client-side JavaScript hace referencia al entorno de ejecuci on de](https://reader030.fdocuments.in/reader030/viewer/2022040915/5e8c43e2926f81074b0ad600/html5/thumbnails/57.jpg)
Referencias
I David Flanagan. “JQuery Pocket Reference” O’Reilly (2010).I Acceso en lınea en Safari
I David Flanagan. “JavaScript: The Definitive Guide” (6th Ed.)O’Reilly.
I Acceso en lınea en Safari
I JQuery API DocumentationI https://api.jquery.com/
Computacion Web (2019/20) Introduccion a JavaScript 57