la magia de jquery

111
Aplicaciones Web con JQUERY Ing. Angel R. Condori Coaquira

Upload: angeldx

Post on 12-Jun-2015

2.602 views

Category:

Education


4 download

DESCRIPTION

Introducción a JQUErY, como agregar recursos a nuestros proyectos web, como animaciones, menús, validaciones, y demás efectos que nos proporciona JQUERY

TRANSCRIPT

Page 1: La magia de jquery

Aplicaciones Web con JQUERY

Ing. Angel R. Condori Coaquira

Page 2: La magia de jquery

¿Cual es el problema con JavaScript?

Page 3: La magia de jquery

JavaScript Fue inicialmente

introducido por Netscape 2.0B3

en Deciembre de 1995,

a.k.a. Mocha, LiveScript, Jscript,

Su nombre oficial fue ECMAScript

Page 4: La magia de jquery

JavaScript se diseño con la

sintaxtis de C, pero adopta

nombres y convenciones de

Java, sin enbargo no estan

relacionados.

Page 5: La magia de jquery

Todos los navegadores modernos interpretan el código JavaScript integrado en las páginas web. Para interactuar con una página web se provee al lenguaje JavaScript de una implementación

del Document Object Model (DOM).

Page 6: La magia de jquery

CLIENTE SERVIDOR

Page 7: La magia de jquery

EL DOM

Page 8: La magia de jquery

EL DOM

Page 9: La magia de jquery

Trabajar con el DOM es

realmente tedioso, es donde

jQuery viene al rescate.

Page 10: La magia de jquery

Introduction a jQuery

Page 11: La magia de jquery

$(“#firstName”).text(“Joe Black”);

$(“button”).click(function() {alert

“Clicked”;});

$(“.content”).hide();

$(“#main”).load(“content.htm”);

$(“<div/

>”).html(“Loading…”).appendTo(“#content”);

$(“#firstName”).text(“Joe Black”);

$(“button”).click(function() {alert

“Clicked”;});

$(“.content”).hide();

$(“#main”).load(“content.htm”);

$(“<div/

>”).html(“Loading…”).appendTo(“#content”);

Una Calidad de vida gracias a jQuery:

Muy compacto y fluido modelo de programación

Page 12: La magia de jquery

¿QUE ES JQUERY?• jQuery es un framework Javascript• un framework, es un producto que sirve como base

para la programación avanzada de aplicaciones, que aporta una serie de funciones o códigos para realizar tareas habituales. Por decirlo de otra manera, framework son unas librerías de código que contienen procesos o rutinas ya listos para usar. Los programadores utilizan los frameworks para no tener que desarrollar ellos mismos las tareas más básicas, puesto que en el propio framework ya hay implementaciones que están probadas, funcionan y no se necesitan volver a programar.

Page 13: La magia de jquery
Page 14: La magia de jquery

• Steve Jobs ha publicado una carta abierta para Adobe, en la página web de Apple, explicando por qué Adobe Flash no será permitido, nunca, en ningún iPhone, iPod Touch o iPad que se fabrique en el futuro.

• 1. Flash se pensó para ser utilizado en ordenadores, con un ratón, nunca en pantallas táctiles que se usan con un dedo. Esto es importante, porque muchas webs que usan Flash basan sus interfaces en el ‘rollover’, que es la función que hace aparecer un menú o cualquier otra cosa cuando detecta que el puntero del ratón pasa por una zona determinada; Esto, con el dedo, no es posible. No existe rollover en ningún dispositivo táctil, por razones lógicas.

• 2. Muchos dicen que Flash es abierto. La propia Adobe lo dice. Pero Flash, no es abierto. Flash es un formato propietario de Adobe y sólo cambia o evoluciona cuando Adobe lo decide. También, tiene el precio que Adobe decide.

• 3. Si se permite que con Flash se puedan crear aplicaciones multiplataforma, las nuevas funcionalidades que Apple quiera desarrollar en el futuro para sus “iDispositivos” sólo serán puestas en práctica cuando Adobe quiera y actualice su Flash.

Page 15: La magia de jquery

• 4. Batería y rendimiento. Apple lleva varios años pidiéndole a Adobe que les enseñen un móvil, cualquier móvil, que no se quede sin batería en un suspiro cuando reproduzca algo en Flash. Adobe nunca se lo han enseñado, y siempre han pedido más tiempo. Apple cree que efectivamente algún día mostrarán un móvil con Flash pero el rendimiento nunca será bueno; ¿Por qué? Porque Flash no se ejecuta vía Hardware, sino vía Software, usando la CPU.

• 5. Sobre Adobe diciendo que los usuarios de Apple se pierden mucho video, desde el primer momento todos los iPhone se han puesto a la venta llevan YouTube preinstalado de serie.

• Conclusión: Flash está muerto, pero como en la película “Los Otros” de Alejandro Amenábar, aún no se han dado cuenta. Por lo tanto, pasemos página y usemos estándares realmente abiertos que se pueden utilizar gratuitamente como HTML5. Con esto, Apple da por zanjada la famosa disputa del Flash en el iPhone.

Page 16: La magia de jquery

JQUERY

• jQuery es una biblioteca de JavaScript, creada inicialmente por John Resig, que permite simplificar la manera de interactuar con los documentos HTML, manipular el árbol DOM, manejar eventos, desarrollar animaciones y agregar interacción con la técnica AJAX a páginas web. Fue presentada el 14 de enero de 2006 en el BarCamp NYC.

Page 17: La magia de jquery

Ventajas de jQuery con respecto a otras alternativas

• Es importante comentar que jQuery no es el único framework que existe en el mercado. Existen varias soluciones similares que también funcionan muy bien, que básicamente nos sirven para hacer lo mismo. Como es normal, cada uno de los frameworks tiene sus ventajas e inconvenientes, pero jQuery es un producto con una aceptación por parte de los programadores muy buena y un grado de penetración en el mercado muy amplio, lo que hace suponer que es una de las mejores opciones.

Page 18: La magia de jquery

Características• Selección de elementos DOM.• Interactividad y modificaciones del árbol DOM, incluyendo soporte para CSS

1-3 y un plugin básico de XPath.• Eventos.• Manipulación de la hoja de estilos CSS.• Efectos y animaciones.• Animaciones personalizadas.• AJAX.• Soporta extensiones.• Utilidades varias como obtener información del navegador, operar con

objetos y vectores, funciones como trim() (elimina los espacios en blanco del principio y final de una cadena de caracteres), etc.

• Compatible con los navegadores Mozilla Firefox 2.0+, Internet Explorer 6+, Safari 3+, Opera 10.6+ y Google Chrome 8+

Page 19: La magia de jquery

Uso

• jQuery consiste en un único fichero JavaScript que contiene las funcionalidades comunes de DOM, eventos, efectos y AJAX.

• La característica principal de la biblioteca es que permite cambiar el contenido de una página web sin necesidad de recargarla, mediante la manipulación del árbol DOM y peticiones AJAX. Para ello utiliza las funciones $() o jQuery().

Función $()

• La forma de interactuar con la página es mediante la función $(), un alias de jQuery(), que recibe como parámetro una expresión CSS o el nombre de una etiqueta HTML y devuelve todos los nodos (elementos) que concuerden con la expresión.

Page 20: La magia de jquery

• $("#tablaAlumnos"); // Devolverá el elemento con id="tablaAlumnos"

• $(".activo"); // Devolverá una matriz de elementos con class="activo“

• Una vez obtenidos los nodos, se les puede aplicar cualquiera de las funciones que facilita la biblioteca.

Page 21: La magia de jquery

Inicio de jQuery

• Comúnmente antes de realizar cualquier acción en el documento con jQuery(), debemos percatarnos de que el documento esté listo. Para ello usamos $(document).ready();, de esta forma:

$(document).ready(function() { //Aquí van todas las acciones del documento.

});

Page 22: La magia de jquery

Versiones

• 26 de agosto de 2006 1.0 Primera versión estable

• 12 de septiembre de 2011 1.6.4 Ultima versión

Page 23: La magia de jquery
Page 24: La magia de jquery
Page 25: La magia de jquery
Page 26: La magia de jquery
Page 27: La magia de jquery
Page 28: La magia de jquery
Page 29: La magia de jquery

Copy the

jquery.js

and the

jquery-vsdoc.js

into your

application folder

Page 30: La magia de jquery

No need to reference the –vsdoc.js

<script src=“jquery.js”/><script src=“jquery.js”/>

Reference it in your markup

Page 31: La magia de jquery

… or just drag it into the file

///<reference path=“jquery.js”/>///<reference

path=“jquery.js”/>

Reference it in your JS files:

Page 32: La magia de jquery

<script src=“http://ajax.googleapis.com/

ajax/libs/jquery/1.2.6/jquery.min.js”>

</script>

<script src=“http://ajax.googleapis.com/

ajax/libs/jquery/1.2.6/jquery.min.js”>

</script>

You can also reference it from Google

Page 33: La magia de jquery

jQuery Core Concepts

Page 34: La magia de jquery

Create HTML elements on the fly

var el = $(“<div/>”)var el = $(“<div/>”)

The Magic $() function

Page 35: La magia de jquery

Manipulate existing DOM elements

$(window).width()$(window).width()

The Magic $() function

Page 36: La magia de jquery

Selects document elements

(more in a moment…)

$(“div”).hide();

$(“div”, $(“p”)).hide();

$(“div”).hide();

$(“div”, $(“p”)).hide();

The Magic $() function

Page 37: La magia de jquery

$(document).ready(function(){…});$(document).ready(function(){…});

Fired when the document is ready for programming.

Better use the full syntax:

$(function(){…});$(function(){…});

The Magic $() function

Page 38: La magia de jquery

It may be used in case of conflict with other frameworks.

jQuery(“div”);jQuery(“div”);

The full name of $() function is

Page 39: La magia de jquery

jQuery uses closures for isolation

(function(){var

jQuery=window.jQuery=window.$=function(){

// … };

})();

(function(){var

jQuery=window.jQuery=window.$=function(){

// … };

})();

The library is designed to be isolated

Page 40: La magia de jquery

var foo = jQuery.noConflict();

// now foo() is the jQuery main function

foo(“div”).hide();

var foo = jQuery.noConflict();

// now foo() is the jQuery main function

foo(“div”).hide();

Avoid $() conflict with other frameworks

// remove the conflicting $ and jQuery

var foo = jQuery.noConflict(true);

// remove the conflicting $ and jQuery

var foo = jQuery.noConflict(true);

Page 41: La magia de jquery

$(“div”).hide()

$(“<span/>”).appendTo(“body”)

$(“:button”).click()

$(“div”).hide()

$(“<span/>”).appendTo(“body”)

$(“:button”).click()

jQuery’s programming philosophy is:

GET >> ACT

Page 42: La magia de jquery

$(“div”).show() .addClass(“main”) .html(“Hello jQuery”);

$(“div”).show() .addClass(“main”) .html(“Hello jQuery”);

Almost every function returns jQuery, which provides a fluent

programming interface and chainability:

Page 43: La magia de jquery

Get > Act

Chainability

The $() function

Three Major Concepts of jQuery

Page 44: La magia de jquery

jQuery Selectors

Page 45: La magia de jquery

$(“*”) // find everything

$(“*”) // find everything

All Selector

Selectors return a pseudo-array of jQuery elements

Page 46: La magia de jquery

$(“div”)

// <div>Hello jQuery</div>

$(“div”)

// <div>Hello jQuery</div>

Basic Selectors

Yes, jQuery implements CSS Selectors!

$(“#usr”)

// <span id=“usr”>John</span>

$(“#usr”)

// <span id=“usr”>John</span>

$(“.menu”)

// <ul class=“menu”>Home</ul>

$(“.menu”)

// <ul class=“menu”>Home</ul>

By Tag:

By ID:

By Class:

Page 47: La magia de jquery

$(“div.main”) // tag and class

$(“table#data”) // tag and id

$(“div.main”) // tag and class

$(“table#data”) // tag and id

More Precise Selectors

Page 48: La magia de jquery

// find by id + by class

$(“#content, .menu”)

// multiple combination

$(“h1, h2, h3, div.content”)

// find by id + by class

$(“#content, .menu”)

// multiple combination

$(“h1, h2, h3, div.content”)

Combination of Selectors

Page 49: La magia de jquery

$(“table td”) // descendants

$(“tr > td”) // children

$(“label + input”) // next

$(“#content ~ div”) // siblings

$(“table td”) // descendants

$(“tr > td”) // children

$(“label + input”) // next

$(“#content ~ div”) // siblings

Hierarchy Selectors

Page 50: La magia de jquery

$(“tr:first”) // first element

$(“tr:last”) // last element

$(“tr:lt(2)”) // index less than

$(“tr:gt(2)”) // index gr. than

$(“tr:eq(2)”) // index equals

$(“tr:first”) // first element

$(“tr:last”) // last element

$(“tr:lt(2)”) // index less than

$(“tr:gt(2)”) // index gr. than

$(“tr:eq(2)”) // index equals

Selection Index Filters

Page 51: La magia de jquery

$(“div:visible”) // if visible

$(“div:hidden”) // if not

$(“div:visible”) // if visible

$(“div:hidden”) // if not

Visibility Filters

Page 52: La magia de jquery

$(“div[id]”) // has attribute

$(“div[dir=‘rtl’]”) // equals to

$(“div[id^=‘main’]”) // starts with

$(“div[id$=‘name’]”) // ends with

$(“a[href*=‘msdn’]”) // contains

$(“div[id]”) // has attribute

$(“div[dir=‘rtl’]”) // equals to

$(“div[id^=‘main’]”) // starts with

$(“div[id$=‘name’]”) // ends with

$(“a[href*=‘msdn’]”) // contains

Attribute Filters

Page 53: La magia de jquery

$(“input:checkbox”) // checkboxes

$(“input:radio”) // radio buttons

$(“:button”) // buttons

$(“:text”) // text inputs

$(“input:checkbox”) // checkboxes

$(“input:radio”) // radio buttons

$(“:button”) // buttons

$(“:text”) // text inputs

Forms Selectors

Page 54: La magia de jquery

$(“input:checked”) // checked

$(“input:selected”) // selected

$(“input:enabled”) // enabled

$(“input:disabled”) // disabled

$(“input:checked”) // checked

$(“input:selected”) // selected

$(“input:enabled”) // enabled

$(“input:disabled”) // disabled

Forms Filters

Page 55: La magia de jquery

$(“select[name=‘ddl’] option:selected”).val()

$(“select[name=‘ddl’] option:selected”).val()

Find Dropdown Selected Item

<select name=“cities”>

<option value=“1”>Tel-Aviv</option>

<option value=“2” selected=“selected”>Yavne</option>

<option value=“3”>Raanana</option>

</select>

<select name=“cities”>

<option value=“1”>Tel-Aviv</option>

<option value=“2” selected=“selected”>Yavne</option>

<option value=“3”>Raanana</option>

</select>

Page 56: La magia de jquery

SELECTORS DEMO

Page 57: La magia de jquery
Page 58: La magia de jquery

Document Traversal

Page 59: La magia de jquery

$(“div”).length$(“div”).length

Returns number of selected elements.

It is the best way to check selector.

A Selector returns a pseudo array of jQuery objects

Page 60: La magia de jquery

$(“div”).get(2) or $(“div”)[2]$(“div”).get(2) or $(“div”)[2]

Returns a 2nd DOM element of the selection

Getting a specific DOM element

Page 61: La magia de jquery

$(“div”).eq(2)$(“div”).eq(2)

Returns a 2nd jQuery element of the selection

Getting a specific jQuery element

Page 62: La magia de jquery

var sum = 0;$(“div.number”).each(

function(){ sum += (+this.innerHTML);});

var sum = 0;$(“div.number”).each(

function(){ sum += (+this.innerHTML);});

this – is a current DOM element

each(fn) traverses every selected element calling fn()

Page 63: La magia de jquery

$(“table tr”).each(function(i){

if (i % 2) $

(this).addClass(“odd”);});

$(“table tr”).each(function(i){

if (i % 2) $

(this).addClass(“odd”);});

$(this) – convert DOM to jQueryi - index of the current element

each(fn) also passes an indexer

Page 64: La magia de jquery

.next(expr) // next sibling

.prev(expr) // previous sibling

.siblings(expr) // siblings

.children(expr) // children

.parent(expr) // parent

.next(expr) // next sibling

.prev(expr) // previous sibling

.siblings(expr) // siblings

.children(expr) // children

.parent(expr) // parent

Traversing HTML

Page 65: La magia de jquery

$(“table td”).each(function() {if ($(this).is(“:first-

child”)) {$

(this).addClass(“firstCol”);}

});

$(“table td”).each(function() {if ($(this).is(“:first-

child”)) {$

(this).addClass(“firstCol”);}

});

Check for expression

Page 66: La magia de jquery

// select paragraph and then find // elements with class ‘header’ inside $(“p”).find(“.header”).show();

// equivalent to:$(“.header”, $(“p”)).show();

// select paragraph and then find // elements with class ‘header’ inside $(“p”).find(“.header”).show();

// equivalent to:$(“.header”, $(“p”)).show();

Find in selected

Page 67: La magia de jquery

$(“<li><span></span></li>”) // li.find(“span”) // span

.html(“About Us”) // span

.andSelf() // span, li.addClass(“menu”) //

span,li .end() // span

.end() // li

.appendTo(“ul.main-menu”);

$(“<li><span></span></li>”) // li.find(“span”) // span

.html(“About Us”) // span

.andSelf() // span, li.addClass(“menu”) //

span,li .end() // span

.end() // li

.appendTo(“ul.main-menu”);

Advanced Chaining

Page 68: La magia de jquery

$(“div”).slice(2, 5).not(“.green”)

.addClass(“middle”);

$(“div”).slice(2, 5).not(“.green”)

.addClass(“middle”);

Get Part of Selected Result

Page 69: La magia de jquery

HTML Manipulation

Page 70: La magia de jquery

$(“p”).html(“<div>Hello $!</div>”);

// escape the content of div.b

$(“div.a”).text($(“div.b”).html());

$(“p”).html(“<div>Hello $!</div>”);

// escape the content of div.b

$(“div.a”).text($(“div.b”).html());

Getting and Setting Inner Content

Page 71: La magia de jquery

// get the value of the checked checkbox$(“input:checkbox:checked”).val();

// get the value of the checked checkbox$(“input:checkbox:checked”).val();

Getting and Setting Values

// set the value of the textbox$(“:text[name=‘txt’]”).val(“Hello”);// set the value of the textbox$(“:text[name=‘txt’]”).val(“Hello”);

// select or check lists or checkboxes$(“#lst”).val([“NY”,”IL”,”NS”]);

// select or check lists or checkboxes$(“#lst”).val([“NY”,”IL”,”NS”]);

Page 72: La magia de jquery

Handling CSS Classes// add and remove class$(“p”).removeClass(“blue”).addClass(“red”);

// add and remove class$(“p”).removeClass(“blue”).addClass(“red”);

// add if absent, remove otherwise$(“div”).toggleClass(“main”);// add if absent, remove otherwise$(“div”).toggleClass(“main”);

// test for class existance if ($(“div”).hasClass(“main”)) { //… }// test for class existance if ($(“div”).hasClass(“main”)) { //… }

Page 73: La magia de jquery

// select > append to the end$(“h1”).append(“<li>Hello $!</li>”);

// select > append to the beginning$(“ul”).prepend(“<li>Hello $!</li>”);

// select > append to the end$(“h1”).append(“<li>Hello $!</li>”);

// select > append to the beginning$(“ul”).prepend(“<li>Hello $!</li>”);

Inserting new Elements

// create > append/prepend to selector$(“<li/>”).html(“9”).appendTo(“ul”);

$(“<li/>”).html(“1”).prependTo(“ul”);

// create > append/prepend to selector$(“<li/>”).html(“9”).appendTo(“ul”);

$(“<li/>”).html(“1”).prependTo(“ul”);

Page 74: La magia de jquery

// select > replace$(“h1”).replaceWith(“<div>Hello</div>”);// select > replace$(“h1”).replaceWith(“<div>Hello</div>”);

Replacing Elements

// create > replace selection$(“<div>Hello</div>”).replaceAll(“h1”);// create > replace selection$(“<div>Hello</div>”).replaceAll(“h1”);

Page 75: La magia de jquery

$(“h3”).each(function(){$(this).replaceWith(“<div>”

+ $(this).html() + ”</div>”);

});

$(“h3”).each(function(){$(this).replaceWith(“<div>”

+ $(this).html() + ”</div>”);

});

Replacing Elements while keeping the content

Page 76: La magia de jquery

// remove all children$(“#mainContent”).empty();// remove all children$(“#mainContent”).empty();

Deleting Elements

// remove selection$(“span.names”).remove();// remove selection$(“span.names”).remove();

// change position$(“p”).remove(“:not(.red)”)

.appendTo(“#main”);

// change position$(“p”).remove(“:not(.red)”)

.appendTo(“#main”);

Page 77: La magia de jquery

$(“a”).attr(“href”,”home.htm”);// <a href=“home.htm”>…</a>$(“a”).attr(“href”,”home.htm”);// <a href=“home.htm”>…</a>

Handling attributes

// set the same as the first one$(“button:gt(0)”).attr(“disabled”,

$(“button:eq(0)”).attr(“disabled));

// set the same as the first one$(“button:gt(0)”).attr(“disabled”,

$(“button:eq(0)”).attr(“disabled));

// remove attribute - enable$(“button”).removeAttr(“disabled”)// remove attribute - enable$(“button”).removeAttr(“disabled”)

Page 78: La magia de jquery

$(“img”).attr({“src” :

“/images/smile.jpg”,“alt” : “Smile”,“width” : 10,“height” : 10

});

$(“img”).attr({“src” :

“/images/smile.jpg”,“alt” : “Smile”,“width” : 10,“height” : 10

});

Setting multiple attributes

Page 79: La magia de jquery

// get style$(“div”).css(“background-color”);// get style$(“div”).css(“background-color”);

CSS Manipulations

// set style $(“div”).css(“float”, “left”);// set style $(“div”).css(“float”, “left”);

// set multiple style properties$(“div”).css({“color”:”blue”,

“padding”: “1em” “margin-right”: “0”, marginLeft: “10px”});

// set multiple style properties$(“div”).css({“color”:”blue”,

“padding”: “1em” “margin-right”: “0”, marginLeft: “10px”});

Page 80: La magia de jquery

// get window heightvar winHeight = $(window).height();

// set element height$(“#main”).height(winHeight);

//.width() – element

//.innerWidth() – .width() + padding

//.outerWidth() – .innerWidth() + border

//.outerWidth(true) – including margin

// get window heightvar winHeight = $(window).height();

// set element height$(“#main”).height(winHeight);

//.width() – element

//.innerWidth() – .width() + padding

//.outerWidth() – .innerWidth() + border

//.outerWidth(true) – including margin

Dimensions

The default unit is Pixel (px)

Page 81: La magia de jquery

// from the document$(“div”).offset().top;

// from the parent element$(“div”).position().left;

// scrolling position$(window).scrollTop();

// from the document$(“div”).offset().top;

// from the parent element$(“div”).position().left;

// scrolling position$(window).scrollTop();

Positioning

Page 82: La magia de jquery

Events

Page 83: La magia de jquery

$(document).ready(function(){//…

});

$(document).ready(function(){//…

});

When the DOM is ready…

Fires when the document is ready for programming.

Uses advanced listeners for detecting.

window.onload() is a fallback.

Page 84: La magia de jquery

// execute always$(“div”).bind(“click”, fn);

// execute only once$(“div”).one(“click”, fn);

// execute always$(“div”).bind(“click”, fn);

// execute only once$(“div”).one(“click”, fn);

Attach Event

Possible event values: blur, focus, load, resize, scroll, unload, beforeunload,

click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave,

change, select, submit, keydown, keypress, keyup, error

(or any custom event)

Page 85: La magia de jquery

jQuery.Event object

Page 86: La magia de jquery

$(“div”).unbind(“click”, fn);$(“div”).unbind(“click”, fn);

Detaching Events

(Unique ID added to every attached function)

Page 87: La magia de jquery

$(“div”).trigger(“click”);$(“div”).trigger(“click”);

Events Triggering

Triggers browser’s event action as well.

Can trigger custom events.

Triggered events bubble up.

Page 88: La magia de jquery

// attach / trigger

elem.blur(fn) / elem.blur()

elem.focus(fn) / elem.focus()

elem.click(fn) / elem.click()

elem.change(fn) / elem.change()

// attach / trigger

elem.blur(fn) / elem.blur()

elem.focus(fn) / elem.focus()

elem.click(fn) / elem.click()

elem.change(fn) / elem.change()

Events Helpers

And many others…

Page 89: La magia de jquery

// use different triggering function$(“div”).triggerHandler(“click”);// use different triggering function$(“div”).triggerHandler(“click”);

Preventing Browser Default Action

// prevent default action in handlerfunction clickHandler(e) {

e.preventDefault();}

// prevent default action in handlerfunction clickHandler(e) {

e.preventDefault();}

// or just return falsefunction clickHandler(e) {return false;}// or just return falsefunction clickHandler(e) {return false;}

Page 90: La magia de jquery

// stop bubbling, keep other handlerfunction clickHandler(e) {

e.stopPropagation();}

// stop bubbling, keep other handlerfunction clickHandler(e) {

e.stopPropagation();}

Preventing Bubbling

// stop bubbling and other handlersfunction clickHandler(e) {

e.stopImmediatePropagation();}

// stop bubbling and other handlersfunction clickHandler(e) {

e.stopImmediatePropagation();}

// or just return falsefunction clickHandler(e) {return false;}// or just return falsefunction clickHandler(e) {return false;}

Page 91: La magia de jquery

// attach live event(“div”).live(“click”, fn);

// detach live event(“div”).die(“click”, fn);

// attach live event(“div”).live(“click”, fn);

// detach live event(“div”).die(“click”, fn);

Live Events

Currently supported events:click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup

Page 92: La magia de jquery

EVENTS DEMO

Page 93: La magia de jquery

Effects

Page 94: La magia de jquery

// just show$(“div”).show();

// reveal slowly, slow=600ms$(“div”).show(“slow”);

// hide fast, fast=200ms$(“div”).hide(“fast”);

// hide or show in 100ms $(“div”).toggle(100);

// just show$(“div”).show();

// reveal slowly, slow=600ms$(“div”).show(“slow”);

// hide fast, fast=200ms$(“div”).hide(“fast”);

// hide or show in 100ms $(“div”).toggle(100);

Showing or Hiding Element

Page 95: La magia de jquery

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

$(“div”).slideToggle(1000);

$(“div”).slideUp();

$(“div”).slideDown(“fast”);

$(“div”).slideToggle(1000);

Sliding Elements

Page 96: La magia de jquery

$(“div”).fadeIn(“fast”);

$(“div”).fadeOut(“normal”);

// fade to a custom opacity$(“div”).fadeTo (“fast”, 0.5);

$(“div”).fadeIn(“fast”);

$(“div”).fadeOut(“normal”);

// fade to a custom opacity$(“div”).fadeTo (“fast”, 0.5);

Fading Elements

Fading === changing opacity

Page 97: La magia de jquery

$(“div”).hide(“slow”, function() {alert(“The DIV is hidden”);

});

$(“div”).show(“fast”, function() {$(this).html(“Hello jQuery”);

}); // this is a current DOM element

$(“div”).hide(“slow”, function() {alert(“The DIV is hidden”);

});

$(“div”).show(“fast”, function() {$(this).html(“Hello jQuery”);

}); // this is a current DOM element

Detecting animation completion

Every effect function has a (speed, callback) overload

Page 98: La magia de jquery

// .animate(options, duration)$(“div”).animate({

width: “90%”,opacity: 0.5,borderWidth:

“5px”

}, 1000);

// .animate(options, duration)$(“div”).animate({

width: “90%”,opacity: 0.5,borderWidth:

“5px”

}, 1000);

Custom Animation

Page 99: La magia de jquery

$(“div”).animate({width: “90%”},100).animate({opacity: 0.5},200).animate({borderWidth:

“5px”});

$(“div”).animate({width: “90%”},100).animate({opacity: 0.5},200).animate({borderWidth:

“5px”});

Chaining Animation

By default animations are queued and than performed one by one

Page 100: La magia de jquery

$(“div”).animate({width: “90%”},

{queue:false, duration:1000})

.animate({opacity : 0.5});

$(“div”).animate({width: “90%”},

{queue:false, duration:1000})

.animate({opacity : 0.5});

Controlling Animations Sync

The first animation will be performed immediately without queuing

Page 101: La magia de jquery

EFFECTS DEMO

Page 102: La magia de jquery

AJAX with jQuery

Page 103: La magia de jquery

$(“div”).load(“content.htm”);

// passing parameters$(“#content”).load(“getcontent.aspx”,

{“id”:”33”,

“type”:”main”});

$(“div”).load(“content.htm”);

// passing parameters$(“#content”).load(“getcontent.aspx”,

{“id”:”33”,

“type”:”main”});

Loading content

Page 104: La magia de jquery

$.get(“test.aspx”, {id:1},function(data)

{alert(data);});

$.post(“test.aspx”, {id:1},function(data)

{alert(data);});

$.get(“test.aspx”, {id:1},function(data)

{alert(data);});

$.post(“test.aspx”, {id:1},function(data)

{alert(data);});

Sending GET/POST requests

Page 105: La magia de jquery

$.getJSON(“users.aspx”, {id:1},function(users){

alert(users[0].name);});

$.getJSON(“users.aspx”, {id:1},function(users){

alert(users[0].name);});

Retrieving JSON Data

Page 106: La magia de jquery

$.getScript(“script.js”,function(){

doSomeFunction();});

$.getScript(“script.js”,function(){

doSomeFunction();});

Retrieving JS Files

Page 107: La magia de jquery

AJAX DEMO

Page 108: La magia de jquery

Extending the Library

Page 109: La magia de jquery

// definitionjQuery.fn.printLine = function(s) {

return jQuery(this).each(function() { this.append(“<div>”+ s +“</div>”);

});};

// usage$(“#log”).printLine(“Hello”);

// definitionjQuery.fn.printLine = function(s) {

return jQuery(this).each(function() { this.append(“<div>”+ s +“</div>”);

});};

// usage$(“#log”).printLine(“Hello”);

Adding Methods

Do not use $ in the method (at least not until next slide)

Page 110: La magia de jquery

(function ($) {

jQuery.fn.printLine = function(s) {return $(this).each(function() {

this.append(“<div>”+ s +“</div>”);

});};

})(jQuery);

(function ($) {

jQuery.fn.printLine = function(s) {return $(this).each(function() {

this.append(“<div>”+ s +“</div>”);

});};

})(jQuery);

Closure to solve the $ issue

Page 111: La magia de jquery

$.expr[‘:’].test = function(o, i, m, s) {

// o – current object in the selection

// i – loop index in the stack

// m – meta data about your selector

// s – stack of all the elements

// return true to include the element

// return false to exclude the element

};

$.expr[‘:’].test = function(o, i, m, s) {

// o – current object in the selection

// i – loop index in the stack

// m – meta data about your selector

// s – stack of all the elements

// return true to include the element

// return false to exclude the element

};

Custom Selectors