Le animazioni di jQuery a volte possono non funzionare nel modo previsto. Questo dipende da diversi fattori, tra cui la catena di animazioni, le proprietà CSS usate, i valori di tali proprietà e la tempistica di esecuzione. Possiamo creare un semplice plugin per effettuare il debugging e il tracciamento delle animazioni. Questo plugin visualizzerà sulla pagina il selettore corrente, il suo contesto, le proprietà CSS usate nell'animazione con i loro valori (specificate come parametro del plugin), i secondi e i millisecondi trascorsi durante l'esecuzione dell'animazione. Vediamo i dettagli.
Ecco il codice del plugin:
(function($) {
$.fn.tracker = function(options) {
var that = this;
that.data('selector', that.selector);
that.data('context', that.context);
var settings = {
styleProperties: []
};
options = $.extend(settings, options);
var props = options.styleProperties;
var styleProps = '', i, len = props.length;
styleProps += '{ ';
for(i = 0; i < len; i += 1) {
var value = that.css(props[i]);
styleProps += props[i] + ':' + ' ' + value + '; ';
}
styleProps += ' }';
return that.each(function() {
var date = new Date();
var log = '[' + that.data('selector') + '] ' +
that.data('context') + ' ' + styleProps
+ ' ' + date.getMilliseconds() + '/ ' + date.getSeconds();
$('<p/>').text(log).appendTo('body');
});
};
})(jQuery);
Per avere un debugging ed un tracking in tempo reale possiamo usare il metodo step()
di animate()
:
$(function(){
$('#test', 'body').click(function() {
$(this).animate({
width: 150,
height: 150,
left: 50
}, {
duration: 'slow',
step: function() {
$('#test', 'body').tracker({styleProperties: ['width', 'height', 'left']});
}
});
});
});
Potete visionare l'esempio finale in questa pagina.