jQuery Loves You

25
Diego Guidi - DotNetMarche

description

"It's all about simplicity": perchè le applicazioni basate su Javascript sono spesso complesse, farraginose e difficilmente manutenibili quando è possibile renderle semplici, eleganti e funzionali? In questa sessione a quattro mani vedremo per prima cosa come sfruttare Javascript al meglio, utilizzando i prototipi, i namespaces, gli oggetti, gli eventi, le chiusure e le altre mille funzionalità di un linguaggio di programmazione troppo spesso sottovalutato. Ci soffermeremo poi su jQuery per analizzare il suo contributo nel semplificare task normalmente tediosi come la manipolazione del DOM, la gestione degli eventi, la programmazione asincrona (AJAX) e le problematiche di compatibilità cross-browser.

Transcript of jQuery Loves You

Page 1: jQuery Loves You

Diego Guidi - DotNetMarche

Page 2: jQuery Loves You
Page 3: jQuery Loves You

DOM tree is clunky to useNo multiple handlers per eventNo high-level functions

Browser incompatibilities

= jQuery to the resque!

Page 4: jQuery Loves You
Page 5: jQuery Loves You

• John Resig http://twitter.com/jeresig

• jQuery 1.0 out (Aug 2006)• jQuery 1.3.2 latest

• Production 19k – Debug 120k• Cross-browser

• Visual Studio 2008 supporthttp://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx

Page 6: jQuery Loves You

var fieldsets = document.getElementsByTagName('fieldset');var legend, fieldset;for (var i = 0; i < fieldsets.length; i++) {

fieldset = fieldsets[i];if (!hasClass(fieldset, 'collapsible')) continue;legend = fieldset.getElementsByTagName('legend');if (legend.length == 0) continue;legend = legend[0];... // Do your job

}

Page 7: jQuery Loves You

$('fieldset.collapsible legend').each(function() {

... // Do your job});

$("table tr:nth-child(odd)").addClass("striped");

Page 8: jQuery Loves You

Separate behavior from structure and style

• HTML => structure• CSS => style• JS => behavior

Page 9: jQuery Loves You

<buttontype="button"

onclick="alert('behavior!');">MyBehavior

</button>

Page 10: jQuery Loves You

<script type="text/javascript">window.onload = function() {

document.getElementById('mybutton').

onclick = behavior;};function behavior() {

alert('behavior!');}</script>

Page 11: jQuery Loves You

$(document).ready(function() {

$("#mybutton").bind('click', function(ev){

alert('behavior!');});

});

document.ready != pageLoadhttp://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same

Page 12: jQuery Loves You

Supports most CSS 1-3 selectors

Select all elements: $('*')

Select all div elements: $('div')

Select element by id: $('#id')

Select all elements with class: $('.class')

Combined: $('div#id.class')

Page 13: jQuery Loves You

Ancestor Descendant Selectors Select all paragraphs inside and element: $('#id p') Select all input elements on a form: $('form input')

Parent Child Selectors Find all paragraphs elements of an element: $('#id > p')

Filtering elements based on values of their attributes Find input with name attribute = value: $('input[name=??]') Find anchor tags that start with mailto: $('a[href^=mailto]') Find anchor tags that end with 'pdf': $('a[href$=pdf]')

Page 14: jQuery Loves You

Convenience pseudo-selectors

:first :last:even :odd:hidden :visible:has :contains:enabled :disabled:animated :selected:not $('div p:not(:hidden)')

Even more! http://docs.jquery.com/selectors

Page 15: jQuery Loves You
Page 16: jQuery Loves You

Fun with attributes get attribute values: $("#foo").attr("myattr") set attribute values: $("#foo").attr("myattr", "newval|myfunc")

Fun with styling check if class name is defined: $("#foo").hasClass("myclass") add/remove class names: $("#foo").addClass("class1 class2") toggle class names: $("#foo").toggleClass("class1 class2") get/set css properties: $("#foo").css("width", "newval|myfunc")

Fun with form elements get a value: $("[name=radioGroup]:checked").val()

Page 17: jQuery Loves You

$("#mydiv") .html("<span>Hello, world!</span>");

$("p").append("<strong>Hello</strong>");$("p").prepend("<strong>Hello</strong>");

$("<p>Hi there!</p>").insertBefore("#mydiv");$("<p>Hi there!</p>").insertAfter("#mydiv ");

$("p").wrap("<div class='wrapped'></div>");

$("p").empty()$("p").clone() - $("p").clone(true)

Page 18: jQuery Loves You

Unified method for establishing event handlersMultiple handlers for each event type on each element $("#mydiv").bind("eventName", data, listener) $("#mydiv").unbind("eventName") $("#mydiv").one("eventName", data, listener) $("#mydiv").trigger("eventName")

Standard event-type names (click, mouseover…) $("#mydiv").click(function(ev) { ... }) $("#mydiv").click()

Namespaced events $("#mydiv").bind("click", f1).bind("click.edit", f2) $("#mydiv").unbind("click.edit")

Page 19: jQuery Loves You

A simpler way to animate your page $("div").hide/show() $("div").toggle()

More difficult… $("div").show("slow", function() { ... })

Could I try to… $("div").fadeIn/fadeOut/fadeTo $("div").slideDown/slideUp/slideToggle

I need more! $("div").animate(properties, duration, easing, callback)

Page 20: jQuery Loves You

Utility functions $.browser $.trim(string) $.getScript(url, callback)

Iterators and filters $.each(array|object, function(index|key, value) { ... }) $.grep(array, function() { //... return true|false; }) var result = $.grep(array, 'a>100');

Extending objects $.extend(target,source1,source2, ... sourceN) var result = $.extend({ }, { a: 1}, { b: 2}, { c: 3}. {d: 4});

Page 21: jQuery Loves You

$("form input").disable();

$.fn.disable = function() { // this => wrapped-set return this.each(function() { // this => wrapped-set element if (typeof this.disabled != "undefined") this.disabled = true; }); }

$("#address input").readOnly(true);

$.fn.readOnly = function(readonly) { return this.filter("input:text") .attr("readonly", readonly) .css("opacity", readonly ? 0.5 : 1.0);}

Page 22: jQuery Loves You

Fetch content $("div").load(url, parameters, callback) $("mydiv").load("/url.ashx", {val: 1}, myfunc) $("mydiv").load("/url.ashx?val=1", myfunc)

Get & Post $.get(url, parameters, callback) $.post(url, parameters, callback) $.getJSON(url, parameters, callback) $.getJSON("/url.ashx", {val: 1}, function(data) { alert(data); })

Ajax events ajaxStart ajaxStop ajaxSend ajaxComplete ajaxSuccess ajaxError

Page 23: jQuery Loves You

$('<div id="loading"><img src="indicator.gif">

</div>').hide().ajaxStart(function() {

$(this).show(); }).ajaxStop(function() {

$(this).hide(); }).appendTo("#container");

$("<div class='foo'>I'm foo!</div> <div>I'm not</div>").filter(".foo").click(function() {

alert("I'm foo!"); }).end().appendTo("#parent");

Page 24: jQuery Loves You

jQuery UIhttp://jqueryui.com

Form pluginhttp://plugins.jquery.com/project/form

More and more…http://plugins.jquery.com

50+ amazing exampleshttp://www.noupe.com/jquery

jQuery in actionhttp://www.manning.com/bibeault

Page 25: jQuery Loves You