<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>CTAPbIu_MABP&#039;s BLOG &#187; animation</title>
	<atom:link href="http://mabp.kiev.ua/tag/animation/feed/" rel="self" type="application/rss+xml" />
	<link>http://mabp.kiev.ua</link>
	<description>энтузиазм = 1/опыт © Старый Мавр</description>
	<lastBuildDate>Sat, 12 May 2012 07:40:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2</generator>
		<item>
		<title>Плавающий текст</title>
		<link>http://mabp.kiev.ua/2011/03/21/floating-text/</link>
		<comments>http://mabp.kiev.ua/2011/03/21/floating-text/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 14:06:00 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://mabp.kiev.ua/?p=1332</guid>
		<description><![CDATA[Вот такая анимация у меня родилась ЖОПА]]></description>
			<content:encoded><![CDATA[<p>Вот такая анимация у меня родилась</p>

<span id="more-1332"></span>

<link rel="stylesheet" type="text/css" media="screen" href="/content/css/floating-text.css"/>
<script type="text/javascript" src="/content/js/floating-text.js"></script>

<div id="float">ЖОПА</div>
]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2011/03/21/floating-text/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Как дебажить анимацию</title>
		<link>http://mabp.kiev.ua/2010/11/29/how-to-debug-animation/</link>
		<comments>http://mabp.kiev.ua/2010/11/29/how-to-debug-animation/#comments</comments>
		<pubDate>Mon, 29 Nov 2010 17:22:22 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://mabp.kiev.ua/?p=1297</guid>
		<description><![CDATA[Дебажить анимацию дело геморрное но нужное. Пост про дебаг поэтому включите, плз, консольку. Когда надо затормозить анимацию где-то посередине, я обычно пишу в консоли что-то вроде setInterval(function(){$(':animated').stop();},500); Но бывает что этого недостаточно тогда в ход идет такой код $("#id").animate({/**/},{ step:function(){ console.log(arguments) } }); Как он работает можно посмотреть на примере анимаций backgroundColor и borderColor backgroundColor [...]]]></description>
			<content:encoded><![CDATA[<p>Дебажить анимацию дело геморрное но нужное.</p>

<span id="more-1297"></span>

<link rel="stylesheet" type="text/css" media="screen" href="/content/css/how-to-debug-animation.css"/>
<script type="text/javascript" src="/content/js/how-to-debug-animation.js"></script>


<p>Пост про дебаг поэтому включите, плз, консольку.</p>

<p>Когда надо затормозить анимацию где-то посередине, я обычно пишу в консоли что-то вроде</p>

<pre><code class="javascript">
setInterval(function(){$(':animated').stop();},500);
</code></pre>

<p>Но бывает что этого недостаточно тогда в ход идет такой код</p>

<pre><code class="javascript">
$("#id").animate({/**/},{
	step:function(){
		console.log(arguments)
	}
});
</code></pre>

<p>Как он работает можно посмотреть на примере анимаций backgroundColor и borderColor</p>

<div class="examples">
	<div id="example1" style="background-color:#0000ff;width:100px;height:100px;"></div>
	<div id="example2" style="border:50px solid  #0000ff;width:   0px;height:   0px;"></div>
	<div>backgroundColor</div>
	<div>borderColor</div>
</div>

<p>Вот такая нелепость и хуй пойми почему....</p>

<p>ЗЫ для тех кто читает через ридер - нелепость в том что анимация бэкграунда начинается всегда с текущего цвета, а бордера - с белого :(</p>
]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2010/11/29/how-to-debug-animation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Букавки</title>
		<link>http://mabp.kiev.ua/2010/09/03/letters/</link>
		<comments>http://mabp.kiev.ua/2010/09/03/letters/#comments</comments>
		<pubDate>Fri, 03 Sep 2010 17:52:06 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[bookmarklet]]></category>

		<guid isPermaLink="false">http://mabp.kiev.ua/?p=1244</guid>
		<description><![CDATA[Сейчас все дружно подумают что я съехал с катушек... Да-да, это летающие букавки! История создания на форуме (function () { var r = function (shift) { return (Math.random() * 255) 1 &#038;&#038; (a = arguments) &#038;&#038; setTimeout(function () { a.callee(letter, opacity - 0.07, fontsize * 0.85); }, 50) &#124;&#124; rem(letter); }, rem = function (l) [...]]]></description>
			<content:encoded><![CDATA[<p>Сейчас все дружно подумают что я съехал с катушек...</p>
<span id="more-1244"></span>

<p>Да-да, это летающие букавки! История создания на <a href="http://pyha.ru/forum/topic/3906">форуме</a></p>

<pre><code class="javascript">
(function () {
	var 
	
	r = function (shift) {
		return (Math.random() * 255) << shift;
	},
  
	print = function (letter, opacity, fontsize) {
		letter.style.opacity = opacity;
		letter.style.fontSize = fontsize+"px";
		~~(opacity * 100) > 1 &#038;&
		(a = arguments) &#038;&
		setTimeout(function () { a.callee(letter, opacity - 0.07, fontsize * 0.85); }, 50) ||
		rem(letter);
	},
   
	rem = function (l) {
		l.parentNode.removeChild(l);
	},
  
	letter = function (html, color) {
		var l = document.createElement("div");
		l.style.textAlign = "center";
		l.style.position = "fixed";
		l.style.width = "100%";
		l.style.fontSize = "700px";
		l.style.top = 0;
		l.style.color = color;
		l.innerHTML = html;
		return document.querySelector("body").appendChild(l);
	};
  
	document.documentElement.addEventListener("keypress", function (e) {
		print(letter(String.fromCharCode(e.charCode).toUpperCase(), "#" + (r(16) + r(8) + r(0)).toString(16)), 1, 700);
		e.preventDefault();
	}, false);
	
})();
</code></pre>

<p>Работает как букмарклет или из фаербага, даже на этом сайте.</p>
<p>ЗЫ сюда выложил чтобы черновики не засорял.</p>

]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2010/09/03/letters/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Симофорчик</title>
		<link>http://mabp.kiev.ua/2010/03/05/simofor/</link>
		<comments>http://mabp.kiev.ua/2010/03/05/simofor/#comments</comments>
		<pubDate>Fri, 05 Mar 2010 16:05:49 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>

		<guid isPermaLink="false">http://mabp.kiev.ua/?p=1220</guid>
		<description><![CDATA[Давно лежит в черновиках, и вот надумал опубликовать. Небольшой пример работы с анимацией на jquery Все очень просто: при ошибке, например, загрузки данных с сервера вылазит маленькое окошечко с сообщением о том что произошла ошибка. Примерно так как на Хабре. Сообщение держиться 5 секунд после чего исчезает. Если на него не навести мышку, если навести [...]]]></description>
			<content:encoded><![CDATA[<p>Давно лежит в черновиках, и вот надумал опубликовать. Небольшой пример работы с анимацией на jquery</p>
<span id="more-1220"></span>

<p>Все очень просто: при ошибке, например, загрузки данных с сервера вылазит маленькое окошечко с сообщением о том что произошла ошибка. Примерно так как на Хабре. Сообщение держиться 5 секунд после чего исчезает. Если на него не навести мышку, если навести то снова появляеться даже если уже наполовину исчезло. Если на него кликнуть то будет держаться пока не кликнеш еще раз. Если сообщения два второе становиться под первое. К сожелению изза дизайна сайта тут положение высчитываеться вврху экрана и если проскролить чуток то оно чуть сползет, поэтому лучше всего смотриться в абсолютным позиционированием контента. Такое позиционирование есть если для создания сраницы исользовался <a href="http://mabp.kiev.ua/2009/12/10/ui-layout/">UI.Layout</a>, так что нужно откорректировать top и left.</p>

<pre><code class="javascript">
	function showMessage(text, error){
		var clicked = false;
		var self = $("&lt;div/&gt;",{
			css:{
				width : "200px",
				height : "60px",
				background : error ? "#ED6060" : "#60ED60",
				position : "relative",
				zIndex : 10,
				textAlign : "center",
				lineHeight : "60px",
				display : "none",
			},
			text : text,
			click : function(){
				clicked = !clicked;
			},
			mouseover : function(){
				self.stop(true, true).fadeIn("slow");
			},
			mouseout : function(){
			if (!clicked){
				self.stop(true, true).fadeOut("slow").queue(function(){
					self.remove();
				});
 			}
		}})
		.appendTo("body")
		.fadeIn("slow")
		.delay(5000)
		.fadeOut("slow")
		.queue(function(){
			self.remove();
		});
	}
</code></pre>

<p>Ну и на последок как водиться примерчик.</p>

<input type="text" name="message" value=""/>
<input type="checkbox" name="error" value=""/>
<select name="effect">
<option value="0">fadeIn/fadeOut</option>
<option value="1">slideDown/slideUp</option>
<option value="2">show/hide</option>
</select>
<select name="speed">
<option value="600">slow</option>
<option value="400">normal</option>
<option value="200">fast</option>
<option value="0">zero</option>
</select>
<input type="button" name="show" value="Click me!"/>

<script type="text/javascript">
jQuery(document).ready(function($){
	function showMessage(text, error){
		var effect = $("[name=effect]").val(),
		speed = parseInt($("[name=speed]").val()),
		clicked = false,
		self = $("<div/>",{
			css:{
				width : "200px",
				height : "60px",
				background : error ? "#ED6060" : "#60ED60",
				position : "relative",
				top: document.documentElement.scrollTop,
				left: 0,
				zIndex : 10,
				textAlign : "center",
				lineHeight : "60px",
				display : "none",
			},
			text : text,
			click : function(){
				clicked = !clicked;
			},
			mouseover : function(){
				self.stop(true, true).fadeIn("slow");
			},
			mouseout : function(){
			if (!clicked){
				self.stop(true, true).fadeOut("slow").queue(function(){
					self.remove();
				});
 			}
		}})
		.appendTo("#qwerty")
		[['fadeIn','slideDown','show'][effect]](speed)
		.delay(5000)
		[['fadeOut','slideUp','hide'][effect]](speed)
		.queue(function(){
			self.remove();
		});
	}
	$("<div/>",{
		id : "qwerty",
		css:{
			position : "absolute",
			top: 0,
			left: 0
		}
	}).appendTo("body");
	$("[name=show]").click(function(){
		showMessage($("[name=message]").val(),$("[name=error]").attr("checked"));
	});
});
</script> ]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2010/03/05/simofor/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>jQuery UI: Progress Bar with custom event</title>
		<link>http://mabp.kiev.ua/2009/03/26/jquery-ui-progress-bar-with-custom-event/</link>
		<comments>http://mabp.kiev.ua/2009/03/26/jquery-ui-progress-bar-with-custom-event/#comments</comments>
		<pubDate>Thu, 26 Mar 2009 14:29:21 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jqueryUI]]></category>
		<category><![CDATA[progress bar]]></category>

		<guid isPermaLink="false">http://mabp.kiev.ua/?p=928</guid>
		<description><![CDATA[Начитался Брэндона Аарона и решил создать небольшое практическое пособие для начинающих по пользовательским событиям (custom events). Напомню что пользовательские события это такие же события как onclick только запускает их не браузер а сам jQuery. Такими событиями являются, например, события "mouseenter", "mouseleave", "ready" и целый набор ajax'овых событий. jQuery также дает возможность создавать пользовательские события, чем [...]]]></description>
			<content:encoded><![CDATA[<p>Начитался <a href="http://brandonaaron.net/blog/2009/03/26/special-events" rel="nofollow external">Брэндона Аарона</a> и решил создать небольшое практическое пособие для начинающих по пользовательским событиям (custom events). Напомню что пользовательские события это такие же события как onclick только запускает их не браузер а сам <a href="http://mabp.kiev.ua/tag/jquery/" title="jQuery">jQuery</a>. Такими событиями являются, например, события "mouseenter", "mouseleave", "ready" и целый набор <a href="http://docs.jquery.com/Ajax_Events" rel="nofollow external">ajax'овых событий</a>. 
<p><a href="http://mabp.kiev.ua/tag/jquery/" title="jQuery">jQuery</a> также дает возможность создавать пользовательские события, чем я и воспользуюсь, создав собственное событие с помощью которого буду обновлять ползунок из <a href="http://mabp.kiev.ua/2009/01/28/modal-dialog-and-progress-bar/">Modal Dialog и Progress Bar</a>. Практическая польза от этого скрипта нулевая, но для демонстрации самое то что доктор прописал. На самом деле весь код описанный в событии можно перенести в стандартный callback 'change'. Итак задача: обновлять ползунок при помощи пользовательского события, при срабатывании события ползунок увеличивается и меняет цвет.</p>
<span id="more-928"></span>

<link rel="stylesheet" type="text/css" media="screen" href="/content/css/jquery-ui-progress-bar-with-custom-event.css"/>
<script type="text/javascript" src="/content/js/jquery-ui-progress-bar-with-custom-event.js"></script>


<pre><code class="html">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;head&gt;
&lt;title&gt;Progress Bar with custom event&lt;/title&gt;
&lt;script src="jquery-1.3.2.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.core.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.resizable.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.draggable.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.dialog.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.progressbar.js" type="text/javascript"&gt;&lt;/script&gt;

&lt;link href="themes/smoothness/ui.core.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.theme.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.resizable.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.dialog.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.progressbar.css" type="text/css" rel="stylesheet" /&gt;

&lt;style&gt;
.ui-progressbar-indicator{
	line-height:40px;
	position:absolute;
	text-indent:-20px;
	left:50%;
}
&lt;/style&gt;

&lt;script type="text/javascript"&gt;
jQuery().ready(function($){

	var counter = 0, 
	dialog = $("&lt;div/&gt;")
		.dialog({modal:true,title:"Заголовок",overlay:{backgroundColor:'#000',opacity: 0.5}})
		.parent().find(".ui-dialog-titlebar-close").hide().end().end(),
	indicator = $("&lt;div/&gt;").addClass("ui-progressbar-indicator").text("0").appendTo(dialog),
	// создаю пользовательское событие myEvent
	// вторым параметром можно передавать null потому что он не используеться в примере
	// но я предпочитаю передавать this, тут this является контекстом функцией переданой параметром в jQuery().ready
	// тоесть window, но если этот объект не window то это единственный способ получить к нему доступ.
	// пример такого использования можно посмотреть в плагине autocomplete
	progressbar = $("&lt;div/&gt;").bind("myEvent", this, function(event,data){
			// event.data хранит данные переданые при создании события
			// тоесть event.data == window
			// data хранит данные переданые при срабатывании события 
			// тоесть data == {counter:counter}
			var 	c = data.counter,
				// процет цвета который заполняет ползунок
				seed = Math.round(255*c/100),
				// в HEX
				green = seed.toString(16),
				// форматируем до двух знаков
				green = green.length == 1 ? "0"+green : green,
				// процент цвета который покидает ползунок
				red = (255 - seed).toString(16),
				// его тоже форматируем
				red = red.length == 1 ? "0"+red : red;
			// увеличиваез значение индикатора
			indicator.text(c+"%");
			// удлиняем ползунок
			$(this).progressbar("value",counter);
			// закрашиваем ползунок новым цветом
			$("div",this).css({background:"#"+red+green+"00"});
		})
		.progressbar({value:0})
		.appendTo(dialog),
	// имитируем длительный процесс
	interval = setInterval(function () {
		counter+=1;
		progressbar.trigger("myEvent",{counter:counter});
		if (counter == 100) {
			clearInterval(interval);
			setTimeout(function(){
				progressbar.progressbar("destroy");
				dialog.dialog("destroy");
				indicator.remove();
			},50);
		}
	}, 50);
});
&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<input type="button" id="example" value="Позырить результат"/>
<br />
<p>Более подробные комментарии можно посмотреть в <a href="http://mabp.kiev.ua/2009/01/28/modal-dialog-and-progress-bar/">Modal Dialog и Progress Bar</a></p>
<br />]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2009/03/26/jquery-ui-progress-bar-with-custom-event/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jQuery UI: Google Gears local store setup</title>
		<link>http://mabp.kiev.ua/2009/03/25/jquery-ui-and-googlegears-local-store-setup/</link>
		<comments>http://mabp.kiev.ua/2009/03/25/jquery-ui-and-googlegears-local-store-setup/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 13:31:31 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jqueryUI]]></category>
		<category><![CDATA[Modal Dialog]]></category>
		<category><![CDATA[progress bar]]></category>

		<guid isPermaLink="false">http://mabp.kiev.ua/?p=926</guid>
		<description><![CDATA[В одной из прошлых статей я рассказывал как совместить Modal Dialog и Progress Bar, теперь пришло время рассказать как это можно использовать. Есть такая штука как Google Gears это интернет акселератор предназначенный по большому счету для продуктов самого Google, таких как почта, календарь, ридер и т.д. Но Google предоставляет возможность устанавливать акселератор и на сторонние [...]]]></description>
			<content:encoded><![CDATA[<p>В одной из прошлых статей я рассказывал как совместить <a href="http://mabp.kiev.ua/2009/01/28/modal-dialog-and-progress-bar/">Modal Dialog и Progress Bar</a>, теперь пришло время рассказать как это можно использовать. Есть такая штука как <a href="http://mabp.kiev.ua/tag/google-gears/">Google Gears</a> это интернет акселератор предназначенный по большому счету для продуктов самого Google, таких как почта, календарь, ридер и т.д. Но Google предоставляет возможность устанавливать акселератор и на сторонние сайты, чем я сейчас и займусь. Самым простым видом акселерации является загрузка в кеш статических файлов, то есть картинок, скриптов и css стилей, хотя теоретически можно загружать и все остальное включая html самой страницы. Я покажу как сделать анимацию загрузки файлов в хранилище <a href="http://mabp.kiev.ua/tag/google-gears/">Google Gears</a>.</p>
<span id="more-926"></span>
<p>Итак начну с начала, мне понадобиться <a href="http://code.google.com/intl/ru/apis/gears/gears_init.js" rel="nofollow external">скрипт</a> который инициализирует <a href="http://mabp.kiev.ua/tag/google-gears/">Google Gears</a>, он написан самим Google и является единственным официальным способом запустить <a href="http://mabp.kiev.ua/tag/google-gears/">Google Gears</a>, и <a href="http://mabp.kiev.ua/tag/jquery-ui/">jQuery UI</a> для создания модального диалога из прошлой статьи. Скрипт создаёт фабрику объектов с которой я буду работать дальше, хотя там и так подробно описано в комментариях. Дальше логика такая - нужно создать новый "склад" и передать все отобранные для кеширования файлы, обновляя после каждого файла ползунок загрузки. Поехали:</p>

<pre><code class="html">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;
&lt;head&gt;
&lt;title&gt;GoogleGears local store setup&lt;/title&gt;
&lt;script src="jquery-1.3.2.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.core.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.resizable.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.draggable.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.dialog.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="ui/ui.progressbar.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;script src="http://code.google.com/intl/ru/apis/gears/gears_init.js" type="text/javascript"&gt;&lt;/script&gt;

&lt;link href="themes/smoothness/ui.core.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.theme.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.resizable.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.dialog.css" type="text/css" rel="stylesheet" /&gt;
&lt;link href="themes/smoothness/ui.progressbar.css" type="text/css" rel="stylesheet" /&gt;
&lt;style&gt;
.ui-progressbar-indicator{
	line-height:40px;
	position:absolute;
	text-indent:-20px;
	left:50%;
}
&lt;/style&gt;
&lt;script type="text/javascript"&gt;
if(!window.console)
	console = {info:function(){}};

jQuery().ready(function($){
	// определяю все с чем буду работать
	var 
	localServer, // сервер
	localStore, // хранилище
	counter = 0, // итератор файлов
	percent = 0, // текущий процент
	store = "myStore", // имя хранилища
	filesToCapture = [  ], // список файлов

	// диалог 
	dialog = $("&lt;div/&gt;")
		// с параметрами но на этот раз без кнопки
		.dialog({modal:true,title:"Заголовок",overlay:{backgroundColor:'#000',opacity: 0.5}})
		// и без крестика
		.parent().find(".ui-dialog-titlebar-close").hide().end().end(),

	// с цифровым индикатором
	indicator = $("&lt;div/&gt;").addClass("ui-progressbar-indicator").text("0")
		.appendTo(dialog),

	// и ползунком
	progressbar = $("&lt;div/&gt;")
		// обновляю значение индикатора
		.progressbar({value:0,change:function(event,ui){indicator.text(percent+"%")}})
		.appendTo(dialog);

	try {
		// пробую создать локальный сервер
		localServer = google.gears.factory.create('beta.localserver');
		window.console.info('Ready!');
		// в нем локальное хранилище
		localServer.createStore(store);
		window.console.info('Created the store');
	} catch (e) {
		// при неудаче - выходим
		window.console.info(e.message);
		return;
	}

	// открываем хранилище
	localStore = localServer.openStore(store);
	// передаем в него список файлов
	localStore.capture(filesToCapture, function (url, success, captureId) {
		counter++;
		// считаем текущий процент
		percent = Math.round(counter/filesToCapture.length*100);
		// обновляем ползунок
		progressbar.progressbar("value",percent)
		// если все файлы закешированы чистим ненужное
		if (counter == filesToCapture.length) {
			progressbar.progressbar("destroy"); 
			dialog.dialog("destroy");
			indicator.remove();
		}
		// на всякий случай пишу все в лог
		window.console.info(url + ' captured ' + (success ? 'succeeded' : 'failed'));
	});
});

&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Примера к сожалению не будет потому что даже если у когото из вас и установлен Google Gears, то у меня нечего особо кешировать, можете посмотреть как выглядит анимация в статье <a href="http://mabp.kiev.ua/2009/01/28/modal-dialog-and-progress-bar/">Modal Dialog и Progress Bar</a></p>
<p>Конечно же интереснее было бы использовать ManagedResourceStore с манифестом, это дает возможность иметь сразу например несколько цветовых схем сайта, но тогда бы не получилось анимировать процесс загрузки.</p>
]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2009/03/25/jquery-ui-and-googlegears-local-store-setup/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Autocomplete</title>
		<link>http://mabp.kiev.ua/2008/04/08/autocomplete/</link>
		<comments>http://mabp.kiev.ua/2008/04/08/autocomplete/#comments</comments>
		<pubDate>Tue, 08 Apr 2008 14:57:44 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[autocomplete]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[UI plugin]]></category>

		<guid isPermaLink="false">http://mabp.localhost/?p=64</guid>
		<description><![CDATA[Prehistory First of all, I want to say, that this plugin was developed for KyivStar, therefore all fine details were studied and stipulated very carefully. For example, what should occur, when the user would reach last element of the list: whether it should rest against the end or begin a cycle all over again. Or [...]]]></description>
			<content:encoded><![CDATA[<h2 class="title">Prehistory</h2>
<br />
<p>First of all, I want to say, that this plugin was developed for <a href="http://www.kyivstar.ua/" rel="nofollow external">KyivStar</a>, therefore all fine details were studied and stipulated very carefully. For example, what should occur, when the user would reach last element of the list: whether it should rest against the end or begin a cycle all over again. Or whether the list should disappear when the cursor is out of it. All this passed through business analysts’ and designer and only then came to me. </p>

<span id="more-64"></span>

<link href="/content/source/autocomplete/autocomplete.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/content/source/autocomplete/jquery.autocomplete.js"></script>
<script type="text/javascript" src="/content/source/jquery.bgiframe.js"></script>
<script type="text/javascript" src="/content/js/autocomplete.js"></script>

<p>On the other hand I tried to make autocomplete multifunctional (multipurpose) and as simple as possible for any person to use it on ones site. Remarkable is that even with switched off javascript the site would not lose functionality, and visitor can enter data anyway. Autocomplete was not made as a filtrator of data entered by the user but the tool which helps the user to fill the form more quickly. </p>
<p>Well-known plugin jquery.suggest was taken as an example. Pieces of which can be identified in some methods. In spite of the fact that I took mechanism, I have added some new functions and have removed some errors. So in last version jquery.suggest the code became more readable thanks to the removal of one check.  But at the end of the list the cursor (illumination) disappears for one position and then again appears at the first element of the list. It happens because jquery (in traversing) always return itself to the object and doesn’t give value to quantity chosen nodes. Another authors fault that he persistently tries to apply $.fn.bgiframe to the list &lt;ul/&gt;, This invention is certainly noble, but I couldn’t deal with this on practice. </p>
<p>Functions that were added: generation of the list from select-box, the limited visible part of the list with scrolling and prefilling of the list for it to look like a select-box. One more events handling onKeyPress. Well-known algorithm of caching MRU was deleted and replaced with my cache algorithm, this takes a lot of memory but it very fast!</p>

<br />
<br />
<h2 class="title">Downloads</h2>
<br />
<p>Last update 14.09.2009!</p>
<br />
<a href="http://mabp.kiev.ua/content/source/autocomplete/autocomplete.html">HTML file with examples (autocomplete.html)</a><br />
<a href="http://mabp.kiev.ua/content/source/autocomplete/jquery.autocomplete.js">Plugin itself (jquery.autocomplete.js)</a><br />
<a href="http://mabp.kiev.ua/content/source/autocomplete/autocomplete.css">Styles (autocomplete.css)</a><br />
<a href="http://mabp.kiev.ua/content/source/autocomplete/select.gif">Little blue arrow (select.gif)</a><br />
<a href="http://mabp.kiev.ua/content/source/autocomplete/progress.gif">Progress bar backgraund image (progress.gif)</a><br />
<a href="http://mabp.kiev.ua/content/source/autocomplete/search.phps">Php backend (search.phps)</a><br />
<p>Copy all this files to your own local web-server in root directory, rename search.phps to search.php and run http://path.to.your.server/autocomplete.html.</p>
<br />
<br />
<h2 class="title">Examples</h2>
<br />
<h4>Example 1: Minimal requirements</h4>
<p>To launch plugin you just need to put in one parameter, the url of php script which generats a list of words. Format of the list can be either xml or json.</p>
<input id="autocomplete1"/>
<pre><code class="javascript">
$("#autocomplete1").autocomplete({
	url:'search.php'
});
</code></pre>

<br />
<h4>Example 2: onSelect event</h4>
<p>Plugin has four public events. First of them is onSelect, it fires where you pick element from the list. You can activate it by left clicking or pressing 'enter' button on the selected item. In this example I use one second delay before searching, and string must be at least 2 characters. The ansver from server will be in xml format so you can omit <b>type</b> property.</p>
<input id="autocomplete2"/>
<pre><code class="javascript">
$("#autocomplete2").autocomplete({
	url:'search.php?type=xml',
	minchar:2,
	delay:1000, // in milliseconds
	onSelect:function(){
		alert(this.ac.val())
	},
	type:'xml'
});
</code></pre>

<br />
<h4>Example 3: onKeyPress</h4>
<p>onKeyPress event fires when you are typing. It can be used to filtrate user input. In this example you can use only alphabetical characters and white space, all other characters will be deleted. The <b>fillin</b> flag will fill in list before user start typing, because of input string is empty the request to the server will also contains empty mask value (i.e. search.php?type=json&#038;mask=). In this case you will see list of one item with text "The list is empty!". The ansver from server will be in json format and you must set <b>type</b> property to 'json'.</p>
<input id="autocomplete3"/>
<pre><code class="javascript">
$("#autocomplete3").autocomplete({
	url:'search.php?type=json',
	onKeyPress:function(){
		var o=this;
		setTimeout(function(){
			o.ac.val(o.ac.val().replace(/[^a-z ]+/g,""))
		},50)
	},
	fillin:true,
	type:'json'
});
</code></pre>

<br />
<h4>Example 4: onError event</h4>
<p>onError and onSuccess is the last two events, onError fires when AJAX has a problems otherwise onSuccess fires when you get answer from server. For example onError fires where you request for non-existing page. Also its an example of how to disable autocomplete. onSuccess get the same parametrs and scope.</p>
<input id="autocomplete4"/>
<pre><code class="javascript">
$("#autocomplete4").autocomplete({
	url:'non_exist.php',
	onError:function(XMLHttpRequest, textStatus, errorThrown){
		this.ac.val(textStatus);
		this.ac.attr({disabled:"disabled"}).css({'background-color':'#d0d0d0'});
		this.ul.hide();
		this.img.unbind("click");
	}
});
</code></pre>

<br />
<h4>Example 5: generation list from &lt;select&gt;</h4>
<p>All previous examples generats autocomplete from AJAX but you also can do this from html code of current page. You can replace existing select-boxes with autocomplete by using <b>source</b> instead of <b>url</b>. You can pass in plugin either string with selectors like '#select.class' or jQuery object $('#select.class'). Pre-filling and digit-only filtrating is enable.</p>
<input id="autocomplete5"/>
<select id="select">
<option>100</option><option>101</option><option>102</option><option>103</option><option>104</option><option>105</option><option>106</option><option>107</option><option>108</option><option>109</option>
<option>110</option><option>111</option><option>112</option><option>113</option><option>114</option><option>115</option><option>116</option><option>117</option><option>118</option><option>119</option>
<option>120</option><option>121</option><option>122</option><option>123</option><option>124</option><option>125</option><option>126</option><option>127</option><option>128</option><option>129</option>
<option>130</option><option>131</option><option>132</option><option>133</option><option>134</option><option>135</option><option>136</option><option>137</option><option>138</option><option>139</option>
<option>140</option><option>141</option><option>142</option><option>143</option><option>144</option><option>145</option><option>146</option><option>147</option><option>148</option><option>149</option>
<option>150</option><option>151</option><option>152</option><option>153</option><option>154</option><option>155</option><option>156</option><option>157</option><option>158</option><option>159</option>
<option>160</option><option>161</option><option>162</option><option>163</option><option>164</option><option>165</option><option>166</option><option>167</option><option>168</option><option>169</option>
<option>170</option><option>171</option><option>172</option><option>173</option><option>174</option><option>175</option><option>176</option><option>177</option><option>178</option><option>179</option>
<option>180</option><option>181</option><option>182</option><option>183</option><option>184</option><option>185</option><option>186</option><option>187</option><option>188</option><option>189</option>
<option>190</option><option>191</option><option>192</option><option>193</option><option>194</option><option>195</option><option>196</option><option>197</option><option>198</option><option>199</option>
</select>

<pre><code class="javascript">
$("#autocomplete5").autocomplete({
	source:"#select",
		onKeyPress:function(){
		var o=this;
		setTimeout(function(){
			o.ac.val(o.ac.val().replace(/[^0-9]+/g,""))
		},50)
	},
	fillin:true
});
</code></pre>

<br />
<h4>Example 6: generation list from array</h4>
<p>If you have no need to use AJAX or have no select-box on your page, you can generate autocomplete from array. Sorry but nested arrays are not supported so you can not use [{a:'a'},{b:'b'}]</p>
<input id="autocomplete6"/>
<pre><code class="javascript">
$("#autocomplete6").autocomplete({
	source:['a','b','c','d','e'],
	fillin:true
});
</code></pre>

<br />
<h4>Example 7: generation list from object</h4>
<p>The same as above. Sorry but nested objects are not supported so you can not use [{a:'a'},{b:'b'}] or {a:{b:c}}</p>
<input id="autocomplete7"/>
<pre><code class="javascript">
$("#autocomplete7").autocomplete({
	source:{a:'a',b:'b',c:'c',d:'d',e:'e'},
	fillin:true
});
</code></pre>

<br />
<h4>Example 8: list position</h4>
<p>Example of list position at the top of input box</p>
<input id="autocomplete8"/>
<pre><code class="javascript">
$("#autocomplete8").autocomplete({
	url:'search.php',
	top:true
});
</code></pre>

<br />
<h4>Example 9: real values</h4>
<p>Example of real values in non writeable fields</p>
<input id="autocomplete9"/>
<pre><code class="javascript">
$("#autocomplete9").autocomplete({
	url:'search.php',
	values : true,
	writable : false,
	onSelect:function(){
		alert(this.pairs[this.ac.val()]);
	}
});
</code></pre>

<br />
<h4>Example 10: alternative setup</h4>
<p>By onSetup event you can change all properties exept 'width' or change behaviour of elements after autocomplete created. This example demonstrate smooth animation to options list.</p>
<input id="autocomplete10"/>
<pre><code class="javascript">
$("#autocomplete10").autocomplete({
	onSetup:function(){
		var self = this;
		self.url = 'search.php';
		self.img.unbind("click")
			.bind("click", function() {
				clearTimeout(self.close);
				self.scroll();
				self.ul.slideToggle("slow")
				self.ac.focus();
			});
	}
});
</code></pre>

<br />
<h4>Example 11: progress animation</h4>
<p>Example of real usage with event hndling and animation</p>
<input id="autocomplete11"/>
<pre><code class="javascript">
$("#autocomplete11").autocomplete({
	url:'/content/polygon/search.php?type=json',
	onSuggest:function(){
		this.ac.css({'background-image': 'url("/content/source/autocomplete/progress.gif")'});
	},
	onError:function(XMLHttpRequest, textStatus, errorThrown){
		this.ac.val(textStatus);
		this.ac.attr({disabled:"disabled"}).css({'background-color':'#d0d0d0','background-image':'none'});
		this.ul.hide();
		this.img.unbind("click");
	},
	onDisplay:function(list){
		this.ac.css({'background-image':'none'});
		if (!list)
		this.ul.append("&lt;div style='line-height:100px;text-decoration:underline;text-align:center;'&gt;[Empty list...]&lt;/div&gt;");
	},
	minchar:2,
	type:'json'
});
</code></pre>
<br />
<h4>Example 12: custom data format</h4>
<p>Example of how to use custom data format</p>
<input id="autocomplete12"/>
<pre><code class="javascript">
$("#autocomplete12").autocomplete({
    source : [{a:'a'},{b:'b'},{c:'c'},{d:'d'},{e:'e'}],
    fillin : true,
    dataHandler : function(mask){
        var self = this;
        return function(i, n) {
        for (var key in n){
            self.cache[mask].push(n[key]);
        }
        self.store[mask] += self.mark(n[key],mask);
        if(self.values &#038;& !self.pairs[n[key]])
            self.pairs[n[key]] = key;
        };
    }
});
</code></pre>

<br />
<h4>Example 13: cascading selectbox</h4>
<p>Example of how create selectbox wich depends on another input field</p>
<input id="autocomplete13"/><input type="checkbox" id="c13"/>
<pre><code class="javascript">
$("#autocomplete13").autocomplete({
    url:function(self){
        var state = $("#c13").attr("checked");
        if (self.ac.data("c13") != state){
            self.ac.data("c13", state);
            self.cache = {};
            self.store = {};
            self.pairs = {};
        }
        return 'search.php?c13='+state;
    }
});
</code></pre>

<br />
<h4>Example 14: autocomplete form selectbox</h4>
<p>Example of how to customize selectbox with plug-in</p>
<select name="myselect" id="autocomplete14">
<option value='Somateria mollissima'>Common Eider</option>
<option value='Crex crex'>Corncrake</option>
<option value='Grus grus'>Common Crane</option>
<option value='Charadrius hiaticula'>Common Ringed Plover</option>
<option value='Gallinago gallinago'>Common Snipe</option>
<option value='Tringa totanus'>Common Redshank</option>
<option value='Sterna hirundo'>Common Tern</option>
<option value='Alcedo atthis'>Common Kingfisher</option>
<option value='Galerida cristata'>Crested Lark</option>
<option value='Corvus corax'>Common Raven</option>
<option value='Emberiza calandra'>Corn Bunting</option>
<option value='Tadorna tadorna'>Common Shelduck</option>
<option value='Bucephala clangula'>Common Goldeneye</option>
<option value='Buteo buteo'>Common Buzzard</option>
<option value='Phoenicurus phoenicurus'>Common Redstart</option>
<option value='Apus apus'>Common Swift</option>
<option value='Sylvia communis'>Common Whitethroat</option>
<option value='Tringa nebularia'>Common Greenshank</option>
<option value='Columba palumbus'>Common Wood Pigeon</option>
<option value='Delichon urbicum'>Common House Martin</option>
<option value='Carduelis cannabina'>Common Linnet</option>
<option value='Cuculus canorus'>Common Cuckoo</option>
<option value='Lophophanes cristatus'>Crested Tit</option>
<option value='Turdus merula'>Common Blackbird</option>
<option value='Actitis hypoleucos'>Common Sandpiper</option>
<option value='Emberiza schoeniclus'>Common Reed Bunting</option>
<option value='Sturnus vulgaris'>Common Starling</option>
<option value='Aythya ferina'>Common Pochard</option>
<option value='Phylloscopus collybita'>Common Chiffchaff</option>
<option value='Falco tinnunculus'>Common Kestrel</option>
<option value='Fringilla coelebs'>Common Chaffinch</option>
<option value='Gallinula chloropus'>Common Moorhen</option>
<option value='Anas crecca'>Common Teal</option>
<option value='Corvus corone'>Carrion Crow</option>
<option value='Periparus ater'>Coal Tit</option>
<option value='Cettia cetti'>Cetti's Warbler</option>
<option value='Motacilla citreola'>Citrine Wagtail</option>
<option value='Calidris ferruginea'>Curlew Sandpiper</option>
<option value='Loxia curvirostra'>Common Crossbill</option>
<option value='Coturnix coturnix'>Common Quail</option>
<option value='Luscinia megarhynchos'>Common Nightingale</option>
<option value='Hydroprogne caspia'>Caspian Tern</option>
<option value='Carpodacus erythrinus'>Common Rosefinch</option>
<option value='Locustella naevia'>Common Grasshopper Warbler</option>
<option value='Melanitta nigra'>Common Scoter</option>
<option value='Bubulcus ibis'>Cattle Egret</option>
<option value='Aythya valisineria'>Canvasback</option>
<option value='Calonectris borealis'>Cory`s Shearwater</option>
<option value='Dromas ardeola'>Crab-Plover</option>
<option value='Cursorius cursor'>Cream-coloured Courser</option>
<option value='Glareola pratincola'>Collared Pratincole</option>
<option value='Charadrius asiaticus'>Caspian Plover</option>
<option value='Larus cachinnans'>Caspian Gull</option>
<option value='Aethia cristatella'>Crested Auklet</option>
<option value='Chaetura pelagica'>Chimney Swift</option>
<option value='Saxicola maura variegata'>Caspian Stonechat</option>
<option value='Acrocephalus fuscus'>Caspian Reed Warbler</option>
<option value='Emberiza cirlus'>Cirl Bunting</option>
<option value='Melanocorypha calandra'>Calandra Lark</option>
<option value='Ficedula albicollis'>Collared Flycatcher</option>
<option value='Emberiza caesia'>Cretzschmar`s Bunting</option>
<option value='Emberiza rutila'>Chestnut Bunting</option>
<option value='Pyrrhocorax pyrrhocorax'>Chough</option>
<option value='Alectoris chukar'>Chukar</option>
</select>
<pre><code class="javascript">
$("select#autocomplete14").autocomplete();
</code></pre>

<br />
<h2 class="title">Notice</h2>
<p>There is no simple way to re-render autocomplete created from select-box or array (object). You just need to re-create it.</p>

<br />
<h2 class="title">Donation</h2>
<p>If you like this plugin please vote for it on <a href="http://plugins.jquery.com/project/jautocomplete" rel="nofollow">jquery site</a></p>

<br />
<h2 class="title">Thanks to</h2>
<ul>
<li>Damir</li>
<li>Connected</li>
<li>Joey</li>
<li>Pasha</li>
<li>Morleydots</li>
<li>Gianfrasoft</li>
<li>Andrea</li>
<li>Ztalker </li>
<li>WooYek</li>
<li>Naden</li>
<li>Andrea Riciputi</li>
</ul>

<br />
<br />
<h2 class="title">Advanced options</h2>
<h4>Properties</h4>
<ul>
<li><b>url</b> - [String|Function] ajax url </li>
<li><b>source</b> - [String|jQuery|Array|Object] css selector or raw html, jQuery object, array [], object {}</li>
<li><b>minchar</b> - [Integer] The minimum number of characters a user has to type before the autocompleter activates (default <b>1</b>)</li>
<li><b>delay</b> - [Integer] The delay in milliseconds the autocompleter waits after a keystroke to activate itself (default <b>50</b> miliseconds)</li>
<li><b>fillin</b> - [Boolean] Pre-fill in (default <b>false</b>)</li>
<li><b>width</b> - [Integer] width of autocomplete (default <b>200</b>)</li>
<li><b>type</b> - [String] type of server responce xml or json (default <b>xml</b>)</li>
<li><b>top</b> - [Boolean] position of the list (default <b>false</b> to the bottom)</li>
<li><b>writable</b> - [Boolean] allows to user write his own option (default <b>true</b>)</li>
<li><b>values</b> - [Boolean] keep values for options (default <b>false</b>)</li>
<li><b>partial</b> - [Boolean] makes request to server after each new letter (default <b>false</b>)</li>

</ul>
<h4>Events</h4>
<ul>
<li><b>onKeyPress</b> - fires when user press a button</li>
<li><b>onSetup</b> - fires once when autocomplit created</li>
<li><b>onSuggest</b> - fires after onKeyPress but before ajax request send</li>
<li><b>onSuccess</b> - fires when AJAX retuns result</li>
<li><b>onError</b> - fires when AJAX retuns error</li>
<li><b>onDisplay</b> - fires before list of items shows</li>
<li><b>onSelect</b> - fires when user picks up from list</li>
</ul>

<h4>Dependences</h4>
<ul>
<li><b>jQuery</b> - requires jQuery 1.2.6 or higher</li>
<li><b>bgiframe</b> - use bgiframe if installed</li>
</ul>]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2008/04/08/autocomplete/feed/</wfw:commentRss>
		<slash:comments>100</slash:comments>
		</item>
		<item>
		<title>FACE по мотивам проекта KuraFire</title>
		<link>http://mabp.kiev.ua/2007/06/26/face-based-on-kurafire-project/</link>
		<comments>http://mabp.kiev.ua/2007/06/26/face-based-on-kurafire-project/#comments</comments>
		<pubDate>Tue, 26 Jun 2007 14:26:35 +0000</pubDate>
		<dc:creator>CTAPbIu_MABP</dc:creator>
				<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Программирование]]></category>
		<category><![CDATA[animation]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://mabp.localhost/?p=140</guid>
		<description><![CDATA[В пятницу лазил по сети и наткнулся на сайте KuraFire на один весьма забавный проект под названием FACE. Решил его поставить себе и поэкспериментировать с ним. На первый взгляд показалось, что все очень красиво и здорово, но при внимательном рассмотрении нашлась пара серьезных недостатков. Самый серьезный из них то, что два таких рисунка нельзя поставить [...]]]></description>
			<content:encoded><![CDATA[<p>В пятницу лазил по сети и наткнулся на сайте <a href="http://kurafire.net/" ref="nofollow">KuraFire</a> на один весьма забавный проект под названием <acronym title="Faruk's Animated CSS Enhancements">FACE</acronym>. Решил его поставить себе и поэкспериментировать с ним. На первый взгляд показалось, что все очень красиво и здорово, но при внимательном рассмотрении нашлась пара серьезных недостатков.</p>
<span id="more-140"></span>
<link rel="stylesheet" type="text/css" media="screen" href="/content/css/face-based-on-kurafire-project.css"/>
<script type="text/javascript" src="/content/js/face-based-on-kurafire-project.js"></script>
<script type="text/javascript" src="/content/source/face.js"></script>

<p>Самый серьезный из них то, что два таких рисунка нельзя поставить на одну страницу. Нет, я дочитал до конца и видел, как автор предлагает в первом диве для анимации указать все id дивов, которые будут анимированы, но этот способ не в счет, а что если я захочу создать блок на лету или прицепить анимацию на кнопку?! Тем более что таким образом анимация работает по очереди, сначала на первом, потом на втором элементе, а не на всех одновременно. Я пробовал переписать код на объектно-ориентированный, но решил, что дешевле написать новый из-за особенностей архитектуры скрипта. Я люблю описывать объект через прототип, и в очередной раз столкнулся с тем, что не могу вызвать метод объекта (из самого объекта используя this) по таймауту.</p>
<p>Вторым недостатком, на мой взгляд, было то, что в примере автор показывает квадрат, который заполняется спирально, а в версии для скачивания он заполняется рядами. Мне тоже захотелось спиралью (а еще столбиками), открыв <a href="http://mabp.kiev.ua/category/programming/css/">CSS</a>, я увидел, что каждый квадрат отпозиционирован отдельно. Вообщем, в этом ничего страшного нет, если большой квадрат состоит из 25-49 маленьких, а если, например, из 100? <a href="http://mabp.kiev.ua/category/programming/css/">CSS</a> разрастается в геометрической прогрессии, создавая неудобство разработчику и пользователю.</p>
<p>Это натолкнуло меня на написание плагина под <a href="http://mabp.kiev.ua/tag/jquery/">jQuery</a>, который бы обладал всеми вышеперечисленными свойствами, то есть быстрота создания, компактность, скорость, программируемость порядка заполнения. ВОТ ОН:</p>

<center><div class="face" id="face1"></div></center>

<p>Для того чтобы запустить пример в работу нужно три строчки кода:</p>

<pre><code class="javascript">
$.face.init(5,5,400,400,6,'#face1');
$.face.resort([0,1,2,3,4,9,14,19,24,23,22,21,20,15,10,5,6,7,8,13,18,17,16,11,12],'#face1');
$.face.start(50,'#face1');
</code></pre>

<p>В первой строчке происходит инициализация объекта, задаются количество столбцов и строк внутри большого квадрата, ширина и высота этого квадрата и id елемента, в котором будет построена сетка.</p>
<p>Во второй задается порядок, в котором будет происходить анимация, в данном конкретном случае - по спирали (по часовой стрелке). Второй параметр нужен, если на странице находиться более одного квадрата.</p>
<p>Третья строчка, собственно, запускает анимацию, эту функцию можно прикрепить, например, к кнопке. Первый параметр - скорость заполнения при загрузке (оптимально от 25 до 100), второй - id</p>

<center><div class="face" id="face2"></div></center>

<center>
<input type="button" id="example1" value="Спираль">
<input type="button" id="example2" value="Сверху вниз">
<input type="button" id="example3" value="Спава налево">
<input type="button" id="example4" value="Из центра">
</center>

<p>Теперь я приведу код собственно самого плагина:</p>

<pre><code class="javascript">
jQuery.extend({
    face : {
        id : null,
        li : [],
        sort : [],
        init : function (cols,rows,width,height,border,id) {
            this.id = id || '#face';
            this.li[this.id] = [];
            for(var i=0,j=cols*rows,l=0,t=0,w=width/cols-border/2,h=height/rows-border/2;i&lt;j;i++,l=i%cols?l+w+border/2:0,t+=i%cols?0:h+border/2)
                this.li[this.id][i] = '&lt;li style="top:'+t+'px;left:'+l+'px;width:'+w+'px;height:'+h+'px;"&gt;&lt;div style="width:'+(w-2)+'px;height:'+(h-2)+'px;"&gt;&lt;div&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/li&gt;';
            this.sort[id] = this.li[id];
        },
        resort : function (array, id) {
            jQuery(id).empty();
            var n = [];
            id = id || this.id;
              for(var key in array)
                n[key] = this.li[id][array[key]];
            this.sort[id] = n;
        },
        start : function (speed,id)
        {
            id = id || this.id;
            jQuery(id).append('&lt;ul&gt;'+this.sort[id].toString().replace(/,/g,'')+'&lt;/ul&gt;');
            jQuery(id+' ul li div').mouseover(function(){jQuery('div',this).animate({opacity:1},'slow','',function(){jQuery(this).animate({opacity:0},'fast');});});
            jQuery.each(jQuery(id+' ul li div div'),function(i,e){setTimeout(function(){jQuery(e).animate({opacity:0},'normal')},i*(speed||50))});
        }
    }
});
</code></pre>

<p>Свойство <span style="color:#000000; font-weight: bold;">id</span> хранит в себе идентификатор последнего запущенного квадрата.</p>
<p>Свойство <span style="color:#000000; font-weight: bold;">li</span> хранит список всех маленьких квадратов в первоначальном порядке.</p>
<p>Свойство <span style="color:#000000; font-weight: bold;">sort</span> хранит уже отсортированный список маленьких квадратов.</p>
<p>Метод <span style="color:#000000; font-weight: bold;">init</span> производит все первоначальные расчеты размеров и позиций маленьких квадратов, образующих сетку.</p>
<p>Метод <span style="color:#000000; font-weight: bold;">resort</span> сортирует маленькие квадраты, в произвольном порядке.</p>
<p>Метод <span style="color:#000000; font-weight: bold;">start</span> запускает анимацию и добавляет анимацию по наведению мыши.</p>

<p>Если кому-то понравился этот плагин - пользуйтесь на здоровье как вам угодно, если нет - ... ну что ж жаль, я старался.</p>]]></content:encoded>
			<wfw:commentRss>http://mabp.kiev.ua/2007/06/26/face-based-on-kurafire-project/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

