SlideShare a Scribd company logo
Advanced jQueryDOM Manipulation, Ajax, PlugIn, andmore..
Mi PresentoFabio FranziniConsulente, Sviluppatore e Trainerblog: www.fabiofranzini.comemail: fabio@fabiofranzini.comtwitter: @franzinifabio
Cos’è jQuery“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.”
Capiamo come usare jQuery senza avere sempre la pappa pronta!!
Filosofia dietro a jQueryTrova qualcosa in qualche modoEsegui qualcosa su questoIl focus principale riguarda l’interazione fra JavaScript e HTML
jQuery è:Solo una funzione!jQuery(): funzione principale$(): Alias di jQuery()jQuery.noConflict()Se si utilizzano librerie diverse che hanno funzioni che si chiamano $
jQuery.noConflict()<script type="text/javascript" src="other_lib.js"></script> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $.noConflict(); 	// Code that uses other library's $ can follow here. </script>var j = jQuery.noConflict(); // Do something with jQueryj("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';<script type="text/javascript" src="other_lib.js"></script> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $.noConflict(); 	jQuery(document).ready(function($) { 		// Code that uses jQuery's $ can follow here. 	}); 	// Code that uses other library's $ can follow here. </script>
jQuery VS $jQuery('#nav')jQuery('div#intro h2')jQuery('#nav li.current a')$('#nav')$('div#intro h2')$('#nav li.current a')
SelettoriCSS 2 e CSS3a[rel]a[rel="friend"]a[href^="http://"]ul#nav > lili#current ~ li (li siblings that follow #current)li:first-child, li:last-child, li:nth-child(3)
Altri tipi di selettoridiv:first, h3:last:header:hidden, :visible:animated:input, :text, :password, :radio, :submit...div:contains(Hello)
Collezioni di oggetti$('div.section') ritorna una collezioni di oggetti jQuery$('div.section').lenght() = “num. dielementi”$('div.section').each(function() {	console.log(this);});$('div.section')[0]$('div.section')[1]$('div.section')[2]
Accedere ai dati$('span#msg').text(‘Ciao Mondo!');$('div#intro').html('<em> Ciao Mondo</em>');$('a.nav').attr('href', 'http://flickr.com/');$('a.nav').attr({	'href': 'http://flickr.com/',	'id': 'flickr'});$('#intro').removeAttr('id');//Alcunimetodiritornano I valori del primo risultatoottenutodalfiltro.var height = $('div#intro').height();var src = $('img.photo').attr('src');var lastP = $('p:last').html()var hasFoo = $('p').hasClass('foo');var email = $('input#email').val();
Gestione dei CSS$('#intro').addClass('highlighted');$('#intro').removeClass('highlighted');$('#intro').toggleClass('highlighted');$('p').css('font-size', '20px');$('p').css({'font-size': '20px', color: 'red'});
Scorrere il DOM$('div.section').parent()$('div.section').next()$('div.section').prev()$('div.section').nextAll('div')$('h1:first').parents()
Gestire gli eventi// OnLoad della pagina$(document).ready(function() {alert('The DOM is ready!');});// OnLoad della pagina$(function() {	alert('The DOM is ready!');});$('a:first').click(function(ev) {ev.preventDefault();$(this).css({backgroundColor: 'orange'});});.........$('a:first').click();
Concatenamento dei MetodiLa maggior parte dei metodi di jQuery restituiscono un altro oggetto jQuery. Solitamente un oggetto che rappresenta l'insieme stesso degli oggetti ritornati in base al filtro. $('div.section').hide().addClass('gone');Alcuni metodi restituiscono un insieme di oggetti diverso. E’ possibile chiamare .end() per ripristinare la precedente collezione$('#intro').css ('colore', '# CCCCCC').Find('a').addClass('highlighted').end().Find('em').CSS ('colore', ' red').end()
Ajax con jQueryjQuery offre un supporto eccellente a Ajax.$('div#intro').load('/some/file.html');Altri metodi:$.get(url, params, callback)$.post(url, params, callback)$.getJSON(url, params, callback)$.getScript(url, callback)
AjaxDEMO
Animazioni//Effetti built-in$('h1').hide('slow');$('h1').slideDown('fast');$('h1').fadeOut(2000);//Concatenazione$('h1').fadeOut(1000).slideDown()$("#block").animate({width: "+=60px",opacity: 0.4,fontSize: "3em",borderWidth: "10px"}, 1500);
AnimazioniDEMO
PluginsjQuery è estendibile grazie ai Plugins disponibili e che possiamo creare noi.Il concetto dietro ai plugin non è altro che l’aggiunta di uno o più metodi all’oggetto jQuery.Esistono un’infinità di Plugins già fatti per i più disparati usi.
Esempio di PlugIn (gmap3) 1/2<script 	type="text/javascript" 	src="http://maps.google.com/maps/api/js?sensor=false"></script><script src="jquery.min.js" type="text/javascript"></script> <script type="text/javascript" src="gmap3-1.0.min.js"></script>...$('#Mappa').gmap3( { 	action: ':addMarker', 	args:{ 		address: "Piazza Bra, Verona", 		map:{ center: true, zoom: 20 } 	} }, {action: 'enableScrollWheelZoom'} );
Esempio di PlugIn (jNotify) 2/2<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.jnotify.js" type="text/javascript"></script>...$(document).ready(function() { 	$('#StatusBar').jnotifyInizialize({ oneAtTime: true });});...$('#addStatusBarError').click(function() { 	$('#StatusBar').jnotifyAddMessage({ 		text: 'This is a permanent error.', 		permanent: true, 		type: 'error' 	}); });
Creare PlugInCreare un file: jquery.nome-plugin.js(function($) { $.fn.nomePlugIn = function() { 		// Codice del Plugin}})(jQuery);$.fn == jQuery.prototype
highlightOnce(function($) {  $.fn.highlightOnce = function() {	return this.each(function() {		// Do something to each item		$(this)			.data('original-color', $(this)			.css('background-color'))			.css('background-color', '#fff47f')			.one('mouseenter', function() {				$(this).animate({					'background-color': 							$(this).data('original-color')				}, 'fast');			});    });}})(jQuery);
highlightOnceDEMO
Creare PlugIn paramerici$.fn.nomePlugIn.defaults = { param1: 'value1',	param2: 'value2'}; $.fn.nomePlugIn = function(options) { options = $.extend($.fn.nomePlugIn.defaults, options); 	....	...};
highlightOnce parametricoDEMO
Plugin CallbackUsiamo come prima i parametri e quindi poi il metodo $.extend$.fn.nomePlugIn.defaults = { param1: 'value1',	param2: 'value2‘,	callback: null}; $.fn.nomePlugIn = function(options) { options = $.extend($.fn.nomePlugIn.defaults, options); 	....	// Eseguire la callback (function.call() => http://bit.ly/a9mYvz)$.isFunction(options.callback) && options.callback.call(this);};
highlightOnce CallbackDEMO
Plugin Namespace 1/2var methods = {    init : function( options ) { … },    show : function( ) { …   },    hide : function( ) { … },    update : function( content ) { … }  };  $.fn.tooltip = function( method ) {    if ( methods[method] ) {      return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));} else if ( typeof method === 'object' || ! method ) {      return methods.init.apply( this, arguments );} else {      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );}  };
Plugin Namespace 2/2$('div').tooltip();$('div').tooltip({ foo : 'bar' }); $('div').tooltip('hide');$('div').tooltip('update', 'Parametro');Metodo ufficiale utilizzato dai Plugin per jQuery
Siamo giunti alla fine..Domande??Tutto chiaro??
Alla prossima ragazzi!Fabio FranziniConsulente, Sviluppatore e Trainerblog: www.fabiofranzini.comemail: fabio@fabiofranzini.comtwitter: @franzinifabio

More Related Content

PDF
Crea un tema compatibile con le ultime novità WordPress
ODP
JavascriptMVC
PDF
jQuery for beginners
PPT
Drupal Cms Prezentace
PDF
Jquery Framework
PDF
Intro to jQuery UI
PPTX
Modelo Php
PDF
Templating WordPress
Crea un tema compatibile con le ultime novità WordPress
JavascriptMVC
jQuery for beginners
Drupal Cms Prezentace
Jquery Framework
Intro to jQuery UI
Modelo Php
Templating WordPress

What's hot (20)

PDF
Introducción a Bolt
PDF
Tworzenie wtyczek dla TinyMCE 4.* - WordUp Kraków
PDF
Silex al límite
ODP
Drupal Theming Hans Rossel
PPT
Ajax With Yui
PPT
jQuery & jQuery Mobile
PPT
Wek14 mysql 2
PDF
Curso Symfony - Clase 5
PPTX
Jquery ui, ajax
PDF
Add tag shortcode
KEY
SmartCSS
PPTX
Introdução ext js 4
PDF
Як досвід компанії перетворився на фреймворк
PDF
スマホウェブの本命 jQueryMobile
PDF
WordPress Customizer
PDF
Poetry in the age of hip-hop
PDF
Pianist and composer Jeff Kowalkowski releases strong new trio album
PDF
jQuery - Javascript para quem não sabe Javascript
PDF
Javascript and jQuery for Mobile
PDF
Jquery2
Introducción a Bolt
Tworzenie wtyczek dla TinyMCE 4.* - WordUp Kraków
Silex al límite
Drupal Theming Hans Rossel
Ajax With Yui
jQuery & jQuery Mobile
Wek14 mysql 2
Curso Symfony - Clase 5
Jquery ui, ajax
Add tag shortcode
SmartCSS
Introdução ext js 4
Як досвід компанії перетворився на фреймворк
スマホウェブの本命 jQueryMobile
WordPress Customizer
Poetry in the age of hip-hop
Pianist and composer Jeff Kowalkowski releases strong new trio album
jQuery - Javascript para quem não sabe Javascript
Javascript and jQuery for Mobile
Jquery2
Ad

Viewers also liked (6)

PDF
Simple Cloud API: accesso semplificato al cloud computing
PPT
Loosely Coupled Complexity - Unleash the power of your domain model
PDF
Java scriptpatterns
PPTX
Michelle Hathaway Mastery Timeline
PPTX
Finggggg
PPTX
Photo presentation
Simple Cloud API: accesso semplificato al cloud computing
Loosely Coupled Complexity - Unleash the power of your domain model
Java scriptpatterns
Michelle Hathaway Mastery Timeline
Finggggg
Photo presentation
Ad

More from Francesca1980 (7)

PPT
Map meshup
PDF
Java scriptpatterns
PDF
Event driven javascript
PDF
Event driven javascript
PPTX
PhoneGap ovvero lo Sviluppo Mobile Nativo con HTML, CSS e JavaScript
ODP
Writing cool web 2.0 apps with GWT and UI Bindings
PDF
Programmazione web libera dai framework
Map meshup
Java scriptpatterns
Event driven javascript
Event driven javascript
PhoneGap ovvero lo Sviluppo Mobile Nativo con HTML, CSS e JavaScript
Writing cool web 2.0 apps with GWT and UI Bindings
Programmazione web libera dai framework

Advanced JQuery

  • 1. Advanced jQueryDOM Manipulation, Ajax, PlugIn, andmore..
  • 2. Mi PresentoFabio FranziniConsulente, Sviluppatore e Trainerblog: www.fabiofranzini.comemail: fabio@fabiofranzini.comtwitter: @franzinifabio
  • 3. Cos’è jQuery“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript.”
  • 4. Capiamo come usare jQuery senza avere sempre la pappa pronta!!
  • 5. Filosofia dietro a jQueryTrova qualcosa in qualche modoEsegui qualcosa su questoIl focus principale riguarda l’interazione fra JavaScript e HTML
  • 6. jQuery è:Solo una funzione!jQuery(): funzione principale$(): Alias di jQuery()jQuery.noConflict()Se si utilizzano librerie diverse che hanno funzioni che si chiamano $
  • 7. jQuery.noConflict()<script type="text/javascript" src="other_lib.js"></script> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $.noConflict(); // Code that uses other library's $ can follow here. </script>var j = jQuery.noConflict(); // Do something with jQueryj("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';<script type="text/javascript" src="other_lib.js"></script> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $.noConflict(); jQuery(document).ready(function($) { // Code that uses jQuery's $ can follow here. }); // Code that uses other library's $ can follow here. </script>
  • 8. jQuery VS $jQuery('#nav')jQuery('div#intro h2')jQuery('#nav li.current a')$('#nav')$('div#intro h2')$('#nav li.current a')
  • 9. SelettoriCSS 2 e CSS3a[rel]a[rel="friend"]a[href^="http://"]ul#nav > lili#current ~ li (li siblings that follow #current)li:first-child, li:last-child, li:nth-child(3)
  • 10. Altri tipi di selettoridiv:first, h3:last:header:hidden, :visible:animated:input, :text, :password, :radio, :submit...div:contains(Hello)
  • 11. Collezioni di oggetti$('div.section') ritorna una collezioni di oggetti jQuery$('div.section').lenght() = “num. dielementi”$('div.section').each(function() { console.log(this);});$('div.section')[0]$('div.section')[1]$('div.section')[2]
  • 12. Accedere ai dati$('span#msg').text(‘Ciao Mondo!');$('div#intro').html('<em> Ciao Mondo</em>');$('a.nav').attr('href', 'http://flickr.com/');$('a.nav').attr({ 'href': 'http://flickr.com/', 'id': 'flickr'});$('#intro').removeAttr('id');//Alcunimetodiritornano I valori del primo risultatoottenutodalfiltro.var height = $('div#intro').height();var src = $('img.photo').attr('src');var lastP = $('p:last').html()var hasFoo = $('p').hasClass('foo');var email = $('input#email').val();
  • 15. Gestire gli eventi// OnLoad della pagina$(document).ready(function() {alert('The DOM is ready!');});// OnLoad della pagina$(function() { alert('The DOM is ready!');});$('a:first').click(function(ev) {ev.preventDefault();$(this).css({backgroundColor: 'orange'});});.........$('a:first').click();
  • 16. Concatenamento dei MetodiLa maggior parte dei metodi di jQuery restituiscono un altro oggetto jQuery. Solitamente un oggetto che rappresenta l'insieme stesso degli oggetti ritornati in base al filtro. $('div.section').hide().addClass('gone');Alcuni metodi restituiscono un insieme di oggetti diverso. E’ possibile chiamare .end() per ripristinare la precedente collezione$('#intro').css ('colore', '# CCCCCC').Find('a').addClass('highlighted').end().Find('em').CSS ('colore', ' red').end()
  • 17. Ajax con jQueryjQuery offre un supporto eccellente a Ajax.$('div#intro').load('/some/file.html');Altri metodi:$.get(url, params, callback)$.post(url, params, callback)$.getJSON(url, params, callback)$.getScript(url, callback)
  • 21. PluginsjQuery è estendibile grazie ai Plugins disponibili e che possiamo creare noi.Il concetto dietro ai plugin non è altro che l’aggiunta di uno o più metodi all’oggetto jQuery.Esistono un’infinità di Plugins già fatti per i più disparati usi.
  • 22. Esempio di PlugIn (gmap3) 1/2<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script><script src="jquery.min.js" type="text/javascript"></script> <script type="text/javascript" src="gmap3-1.0.min.js"></script>...$('#Mappa').gmap3( { action: ':addMarker', args:{ address: "Piazza Bra, Verona", map:{ center: true, zoom: 20 } } }, {action: 'enableScrollWheelZoom'} );
  • 23. Esempio di PlugIn (jNotify) 2/2<script src="jquery.min.js" type="text/javascript"></script> <script src="jquery.jnotify.js" type="text/javascript"></script>...$(document).ready(function() { $('#StatusBar').jnotifyInizialize({ oneAtTime: true });});...$('#addStatusBarError').click(function() { $('#StatusBar').jnotifyAddMessage({ text: 'This is a permanent error.', permanent: true, type: 'error' }); });
  • 24. Creare PlugInCreare un file: jquery.nome-plugin.js(function($) { $.fn.nomePlugIn = function() { // Codice del Plugin}})(jQuery);$.fn == jQuery.prototype
  • 25. highlightOnce(function($) { $.fn.highlightOnce = function() { return this.each(function() { // Do something to each item $(this) .data('original-color', $(this) .css('background-color')) .css('background-color', '#fff47f') .one('mouseenter', function() { $(this).animate({ 'background-color': $(this).data('original-color') }, 'fast'); }); });}})(jQuery);
  • 27. Creare PlugIn paramerici$.fn.nomePlugIn.defaults = { param1: 'value1', param2: 'value2'}; $.fn.nomePlugIn = function(options) { options = $.extend($.fn.nomePlugIn.defaults, options); .... ...};
  • 29. Plugin CallbackUsiamo come prima i parametri e quindi poi il metodo $.extend$.fn.nomePlugIn.defaults = { param1: 'value1', param2: 'value2‘, callback: null}; $.fn.nomePlugIn = function(options) { options = $.extend($.fn.nomePlugIn.defaults, options); .... // Eseguire la callback (function.call() => http://bit.ly/a9mYvz)$.isFunction(options.callback) && options.callback.call(this);};
  • 31. Plugin Namespace 1/2var methods = { init : function( options ) { … }, show : function( ) { … }, hide : function( ) { … }, update : function( content ) { … } }; $.fn.tooltip = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call(arguments, 1));} else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments );} else { $.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );} };
  • 32. Plugin Namespace 2/2$('div').tooltip();$('div').tooltip({ foo : 'bar' }); $('div').tooltip('hide');$('div').tooltip('update', 'Parametro');Metodo ufficiale utilizzato dai Plugin per jQuery
  • 33. Siamo giunti alla fine..Domande??Tutto chiaro??
  • 34. Alla prossima ragazzi!Fabio FranziniConsulente, Sviluppatore e Trainerblog: www.fabiofranzini.comemail: fabio@fabiofranzini.comtwitter: @franzinifabio