Tag Archives: html
2. Introducción a Javascript.
-
Lenguaje de scripting típicamente usado para controlar el funcionamiento de un navegador web y para agregar interactividad a documentos HTML.
-
También utilizado como lenguaje de scripting de propósito general y para programar lógica del lado del servidor en aplicaciones web. Ver Nodejs Muy recomendado!!! Por ejemplo: Crear un servidor web con javascript y nodejs es re-fácil:
1
2
3
4
5
6
7
8
9
10var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');Para correr el servidor, ponga el código anterior en un archivo llamado servidor.js y ejecute la siguiente línea en una terminal:
1$ node servidor.js
Sintaxis
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | // Tomado sin permiso de http://javascript.infogami.com/Javascript_in_Ten_Minutes ////////////////////////////////////// // Basic Types var intValue = 1; var floatValue = 3.0; var stringValue = "This is a string\n"; /////////////////////////////////////// // Array var emptyList = []; var homogenousList = [1, 2, 3]; var heterogenousList = ["one", 2, 3.0]; /////////////////////////////////////// // Property Map // var emptyMap = {}; var homogenousMap = {"one": 1, "two": 2, "three": 3}; var heterogenousMap = {"one": 1, "two": "two", "three": 3.0}; /////////////////////////////////////// // Functions as values // var callable = function (message) { // <-- notice assignment window.alert("Callable called with message = " + message); } function createClosure(initial) { var res = function () { initial = initial + 1; window.alert("Closure with modified state " + initial); } return res; } /////////////////////////////////////// // Functions as arguments // function callCallable(f, x) { f(x); } function composeCallables(f, g, x) { f(g(x)); } /////////////////////////////////////// // Objects // function MyObject(name, value) { this.name = name; this.value = value; } /////////////////////////////////////// // Objects with Member Functions // function Message(message) { this.message = message; } Message.prototype.show = function() { window.alert("Message.show() with message = " + this.message); } |
Document Object Model
El DOM es una representación programática de un documento XML o HTML. En un navegador, se utiliza para acceder o modificar secciones del documento HTML que se está visualizando usando Javascript.
Un ejemplo simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <article id="primer_articulo"> <h1>Titulo del artículo</h1> <p class="resumen"><img src="http://foo.com/bar.jpg" alt="Una foto cuadrada y nítida">Blah Blah Blah Blah</p> </article> <script type="text/javascript"> var image = document.getElementById('primer_articulo').childNodes[3].childNodes[0]; for( var x = 0; x < image.attributes.length; x++ ) { if( image.attributes[x].nodeName.toLowerCase() == 'alt' ) { window.alert('El alt de la imagen es: ' + image.attributes[x].nodeValue ); } } </script> |
jQuery
El problema con la API del DOM es que no es muy compacta y existen muchas diferencias entre las implementaciones en diferentes navegadores. Como ejemplo mire este artículo que discute en mas de 5000 palabras como suscribirse a un evento click
Una alternativa altamente adoptada es la librería jQuery que brinda una API mucho mas compacta, métodos que encapsulan las diferencias entre navegadores y otras APIs para diferentes tareas como ajax,
Un ejemplo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | <!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Parrafos</title> <style type="text/css" media="screen"> p { font-family: "Helvetica Neue", "Helvetica", "Arial", "sans-serif"; font-size:18px; color: #333; border: 1px solid #AAA; width:400px; margin:20px auto; cursor: pointer; } </style> </head> <body> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <p> Readymade quinoa beard shoreditch bicycle rights. Synth tofu ethical, biodiesel before they sold out PBR messenger bag readymade mcsweeney’s seitan echo park brooklyn pitchfork wayfarers tumblr. Quinoa bicycle rights salvia, mlkshk carles yr tattooed marfa high life helvetica artisan wayfarers next level butcher gluten-free. </p> <script src="jquery-1.7.1.min.js" type="text/javascript"></script> <script src="jquery.color.min.js" type="text/javascript"></script> <script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $('p').click(function(){ $('p').animate({ 'color':"#333", 'font-size': '18px', 'padding': '0px' }); $(this).animate({ 'color':"#0000AA", 'font-size': '22px', 'padding': '10px' }); }); }); </script> </body> </html> |
Algunas cosas nuevas en HTML5
Almacenamiento local de datos
1 2 | window.localStorage.setItem('value', area.value); window.localStorage.setItem('timestamp', (new Date()).getTime()); |
Bases de datos locales
1 2 3 4 | var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); //5MB db.transaction(function(tx) { tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback); }); |
Cache de aplicaciones
Permite cargar un documento una vez y utilizarlo después cuando no haya conexión a internet.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <html manifest="cache.appcache"> --- window.applicationCache.addEventListener('updateready', function(e) { if (window.applicationCache.status == window.applicationCache.UPDATEREADY) { window.applicationCache.swapCache(); if (confirm('A new version of this site is available. Load it?')) { window.location.reload(); } } }, false); --- cache.appcache: CACHE MANIFEST # version 1.0.0 CACHE: /html5/src/logic.js /html5/src/style.css /html5/src/background.png NETWORK: * |
Web workers
Permiten iniciar hilos de ejecución paralelos, haciendo que las aplicaciones respondan mucho mejor.
1 2 3 4 5 6 7 8 9 10 | // En main.js: var worker = new Worker('task.js'); worker.onmessage = function(event) { alert(event.data); }; worker.postMessage('data'); // En tasks.js self.onmessage = function(event) { // Do some work. self.postMessage("recv'd: " + event.data); }; |
Web sockets
Permiten dejar establecida la comunicación con un servidor.
1 2 3 4 5 6 | var socket = new WebSocket('ws://html5rocks.websocket.org/echo'); socket.onopen = function(event) { socket.send('Hello, WebSocket'); }; socket.onmessage = function(event) { alert(event.data); } socket.onclose = function(event) { alert('closed'); } |
Notificaciones
Permiten mostrar un mensaje por fuera de la ventana del navegador, incluso cuando está minimizado.
1 2 3 4 5 6 | if (window.webkitNotifications.checkPermission() == 0) { window.webkitNotifications.createNotification(imagen, titulo, texto).show(); } else { window.webkitNotifications.requestPermission(); } |
Geo-locación
Permite preguntar al sistema operativo la ubicación geográfica del usuario.
1 2 3 4 5 6 7 8 | if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var latLng = new google.maps.LatLng( position.coords.latitude, position.coords.longitude); var marker = new google.maps.Marker({position: latLng, map: map}); map.setCenter(latLng); }, errorHandler); } |
Ejercicios
- Programe un carrusel de imágenes usando html, css y javascript.
Taller HTML5
Esquema del curso
- Introducción a HTML y CSS.
- Introducción a Javascript.
- Programación gráfica con <canvas> y Javascript.
- Programación de aplicaciones estilo escritorio.
- HTML5 como sistema de desarrollo para aplicaciones móviles y de escritorio.
1. Introducción a HTML y CSS.
Definición
Hipertext Markup Language es un lenguage para anotar texto de manera que sea sintácticamente distinguible de ese texto. Es usado por los navegadores web para describir e interpretar documentos de texto, imágenes y sonido y presentarlos como páginas web audibles o visibles.
(Español) Insertar atributos de un elemento HTML como contenido con CSS.
Sorry, this entry is only available in Español.