Date post: | 07-Dec-2014 |
Category: |
Documents |
Upload: | francesca1980 |
View: | 3,545 times |
Download: | 0 times |
Advanced jQuery
DOM Manipulation, Ajax, PlugIn, and more..
Mi Presento
Fabio FranziniConsulente, Sviluppatore e
Trainer
blog: www.fabiofranzini.comemail: [email protected]
twitter: @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 jQuery
• Trova qualcosa in qualche modo• Esegui qualcosa su questo• Il 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>
<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>
var j = jQuery.noConflict(); // Do something with jQuery j("div p").hide(); // Do something with another library's $() $("content").style.display = 'none';
jQuery VS $
• jQuery('#nav')• jQuery('div#intro h2')• jQuery('#nav li.current a')• $('#nav')• $('div#intro h2')• $('#nav li.current a')
Selettori
• CSS 2 e CSS3– a[rel]– a[rel="friend"]– a[href^="http://"]– ul#nav > li– li#current ~ li (li siblings that follow
#current)– li:first-child, li:last-child, li:nth-child(3)
Altri tipi di selettori
• div:first, h3:last• :header• :hidden, :visible• :animated• :input, :text, :password, :radio, :subm
it...• div:contains(Hello)
Collezioni di oggetti
$('div.section') ritorna una collezioni di oggetti jQuery
$('div.section').lenght() = “num. di elementi”$('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');
//Alcuni metodi ritornano I valori del primo risultato ottenuto dal filtro.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
$('a:first').click(function(ev) { ev.preventDefault();$(this).css({backgroundColor: 'orange'});
});.........$('a:first').click();
// OnLoad della pagina$(document).ready(function() {
alert('The DOM is ready!');});
// OnLoad della pagina$(function() {
alert('The DOM is ready!');});
Concatenamento dei Metodi
$('div.section').hide().addClass('gone');
La 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.
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 jQuery
jQuery 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)
Ajax
DEMO
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);
Animazioni
DEMO
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 PlugIn
Creare 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);
highlightOnce
DEMO
Creare PlugIn paramerici
$.fn.nomePlugIn.defaults = { param1: 'value1',param2: 'value2'
};
$.fn. nomePlugIn = function(options) { options = $.extend($.fn.nomePlugIn.defaults ,
options); .......
};
highlightOnce parametrico
DEMO
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 Callback
DEMO
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
Trainer
blog: www.fabiofranzini.comemail: [email protected]
twitter: @franzinifabio