<?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>Herberth Amaral &#187; JavaScript</title> <atom:link href="http://herberthamaral.com/category/javascript/feed/" rel="self" type="application/rss+xml" /><link>http://herberthamaral.com</link> <description>Software development adventures</description> <lastBuildDate>Thu, 26 Aug 2010 13:59:42 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.0.1</generator> <item><title>Quando uma deficiência pode se tornar uma feature numa linguagem de programação</title><link>http://herberthamaral.com/2010/07/quando-uma-deficiencia-pode-se-tornar-uma-feature-numa-linguagem-de-programacao/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=quando-uma-deficiencia-pode-se-tornar-uma-feature-numa-linguagem-de-programacao</link> <comments>http://herberthamaral.com/2010/07/quando-uma-deficiencia-pode-se-tornar-uma-feature-numa-linguagem-de-programacao/#comments</comments> <pubDate>Thu, 29 Jul 2010 13:34:55 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[PHP]]></category> <category><![CDATA[Python]]></category> <category><![CDATA[agile]]></category> <category><![CDATA[ruby]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=665</guid> <description><![CDATA[Estava lendo um antigo post do Obie Fernandez onde ele lista várias razões do porquê Java é uma porcaria (em tom de brincadeira, claro =). Numa das razões citadas por ele, há o seguinte trecho: 8 ) Java has good debugging support Java has great and powerful debugging (which is very necessary since most Java [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fquando-uma-deficiencia-pode-se-tornar-uma-feature-numa-linguagem-de-programacao%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fquando-uma-deficiencia-pode-se-tornar-uma-feature-numa-linguagem-de-programacao%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div><p>Estava lendo um <a href="http://www.jroller.com/obie/entry/top_10_reasons_why_java">antigo post</a> do <a href="http://obiefernandez.com/">Obie Fernandez </a>onde ele lista várias razões do porquê Java é uma porcaria (em tom de brincadeira, claro =). Numa das razões citadas por ele, há o seguinte trecho:</p><blockquote><p> 8 ) Java has good debugging support</p><p>Java has great and powerful debugging (which is very necessary since most Java code sucks so much ass). Ruby has ridiculously pitiful debugging support, which means our code actually needs to be well-tested and readable.</p></blockquote><p>Traduzindo:</p><blockquote><p> 8 ) Java possui um bom suporte a debugging</p><p>Java possui um excelente e poderoso debugging (o que é necessário, já que boa parte de códigos em Java são muito ruins). Ruby tem um suporte a debugging lamentavelmente ridículo, o que significa que nosso código realmente precisa ser bem testado e legível.</p></blockquote><p>Vendo por este lado, Ruby é uma excelente linguagem para quem sabe fazer direito e uma droga pra quem está acostumado com IDEs com Intellisense e checagem de erros pelo compilador.</p><p>Outras linguagens possuem problemas que são resolvidos facilmente com o uso de testes unitários. Um problema clássico que acontece com o PHP, o <a href="http://en.wikipedia.org/wiki/White_screen_of_death#PHP_web_applications">White Screen of Death</a> (um erro que acontece com o script que nenhuma informação ou mensagem de erro é apresentada), pode ser resolvido com o uso de testes.</p><p>Alguns &#8220;problemas&#8221; advindos com linguagens dinâmicas é com a mudança de tipo de uma determinada variável, por exemplo:</p><div class="codecolorer-container python default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="python codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #ff7700;font-weight:bold;">class</span> Op:<br /> &nbsp; &nbsp; x = <span style="color: #ff4500;">1</span> &nbsp; &nbsp; <br /> &nbsp; &nbsp; y = <span style="color: #ff4500;">3</span><br /> &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">def</span> soma<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:<br /> &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>.<span style="color: black;">x</span> + <span style="color: #008000;">self</span>.<span style="color: black;">y</span><br /> op = Op<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span><br /> op.<span style="color: black;">y</span> = <span style="color: #483d8b;">&quot;aha!&quot;</span><br /> op.<span style="color: black;">soma</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span> <span style="color: #808080; font-style: italic;">#Ooopss... TypeError</span></div></div><p>Este é um tipo de problema que vem com a checagem de tipo em tempo de execução, ao invés de ser feito em tempo de compilação. Muitas pessoas que não possuem a mesma visão do Obie, encaram isto como um problema.</p><h3> Opinionated Software</h3><p>Um trecho muito conhecido do <a href="http://gettingreal.37signals.com/">Getting Real</a> é o trecho que fala sobre <a href="http://gettingreal.37signals.com/ch04_Make_Opinionated_Software.php">opinionated software</a>:</p><blockquote><p> <strong>Your app should take sides</strong></p><p>Some people argue software should be agnostic. They say it&#8217;s arrogant for developers to limit features or ignore feature requests. They say software should always be as flexible as possible.</p><p>We think that&#8217;s bullshit. The best software has a vision. The best software takes sides. When someone uses software, they&#8217;re not just looking for features, they&#8217;re looking for an approach. They&#8217;re looking for a vision. Decide what your vision is and run with it.</p></blockquote><p>Traduzindo:</p><blockquote><p> <strong>Seu aplicativo deve tomar partido</strong></p><p>Algumas pessoas defendem que o software deve ser agnóstico. Dizem que é arrogante da parte dos desenvolvedores limitar a funcionalidade ou ignorar pedidos de novos recursos. Dizem que o software deve ser sempre o mais flexível possível.</p><p>Para nós isso é papo-furado. O melhor software traz consigo uma visão. O melhor software toma partido. Quando alguém usa um software, não está procurando apenas recursos, está procurando uma abordagem. Está procurando uma visão. Decida qual é sua visão e atenha-se a ela.</p></blockquote><p>Esta mesma idéia permeia linguagens de programação. Você não achará um linguagem que sirva bem para todos os tipos de casos. Python, por exemplo, não é uma boa linguagem se você quiser usar threads pesadamente. Erlang, apesar de ser uma excelente escolha para programação distribuída e paralela, enfrenta um certo preconceito por ser funcional e não ter suporte à orientação a objetos. C#.NET é uma boa linguagem para criação de aplicativos comerciais, mas não é totalmente portável para todas as plataformas (o Mono mal suporta o .NET 3.5 e o framework já está na versão 4).</p><p><strong>Conclusão</strong>: antes de reclamar de uma linguagem de programação, saiba que toda linguagem tem um <em>approach</em>, um foco e veja se esta &#8220;falha&#8221; pode ser algo útil&#8230; muitas vezes o é <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><p>Sem posts relacionados.</p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/quando-uma-deficiencia-pode-se-tornar-uma-feature-numa-linguagem-de-programacao/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>[jQuery para apressados] Modularizando sua aplicação com Module Pattern e jQuery</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-modularizando-sua-aplicacao-com-module-pattern-e-jquery/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-modularizando-sua-aplicacao-com-module-pattern-e-jquery</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-modularizando-sua-aplicacao-com-module-pattern-e-jquery/#comments</comments> <pubDate>Thu, 22 Jul 2010 09:58:21 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category> <category><![CDATA[design patterns]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=647</guid> <description><![CDATA[O module pattern é um padrão de projetos para JavaScript que permite que você use closures autoexecutáveis para criação de &#8220;classes&#8221; com &#8220;atributos privados&#8221;. Calma que eu explico :0) O JavaScript não possui meios de declarar uma variável como &#8220;protected&#8221; ou &#8220;private&#8221;, como você costuma ver em linguagens como Java, C# e C++. Como uma [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-modularizando-sua-aplicacao-com-module-pattern-e-jquery%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-modularizando-sua-aplicacao-com-module-pattern-e-jquery%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div><p>O module pattern é um padrão de projetos para JavaScript que permite que você use <a href="https://developer.mozilla.org/en/JavaScript/Guide/Closures">closures</a> autoexecutáveis para criação de &#8220;classes&#8221; com &#8220;atributos privados&#8221;.</p><p>Calma que eu explico :0)</p><p>O JavaScript não possui meios de declarar uma variável como &#8220;protected&#8221; ou &#8220;private&#8221;, como você costuma ver em linguagens como Java, C# e C++. Como uma forma de &#8220;proteger&#8221; alguns objetos de acesso externo, desenvolveu-se uma técnica chamada &#8220;module pattern&#8221;, que tem o poder de encapsular e restringir o acesso a tais objetos.</p><p>Antes de irmos para o module pattern, de uma olhada numa função autoexecutável:</p><div class="codecolorer-container javascript default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> <br /> &nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'olá, mundo!'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div><p>Interessante, não? Eu estou criando uma função e executando-a ao mesmo tempo. Note que eu posso passar um parâmetro pra ela se for necessário:</p><div class="codecolorer-container javascript default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>nome<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> <br /> &nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Olá, '</span><span style="color: #339933;">+</span>nome<span style="color: #339933;">+</span><span style="color: #3366CC;">'!'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// Olá, Herberth</span><br /> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Herberth'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div><p>O module pattern funciona do mesmo jeito:</p><div class="codecolorer-container javascript default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #003366; font-weight: bold;">var</span> CarrinhoDeCompras <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br /> &nbsp; <span style="color: #003366; font-weight: bold;">var</span> itens <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> &nbsp;<span style="color: #006600; font-style: italic;">// variável &quot;privada&quot;. Não pode ser acessada externamente</span><br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> hasItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">return</span> jQuery.<span style="color: #660066;">inArray</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span>itens<span style="color: #009900;">&#41;</span><span style="color: #339933;">!=-</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> addItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>hasItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; itens.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">else</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Opa! O item '</span><span style="color: #339933;">+</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">+</span><span style="color: #3366CC;">' já está selecionado'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> removeItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> position <span style="color: #339933;">=</span> jQuery.<span style="color: #660066;">inArray</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span>itens<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>hasItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">delete</span> itens<span style="color: #009900;">&#91;</span>position<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">else</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Opa, não temos o item '</span><span style="color: #339933;">+</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">+</span><span style="color: #3366CC;">' no carrinho de compras'</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// retorna um objeto com o que será visível pro mundo</span><br /> &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// note que o array itens não está incluído</span><br /> &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>removeItem<span style="color: #339933;">:</span>removeItem<span style="color: #339933;">,</span>addItem<span style="color: #339933;">:</span>addItem<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br /> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> <br /> <span style="color: #006600; font-style: italic;">//poderíamos utilizar o código acima da seguinte forma:</span><br /> <br /> <br /> CarrinhoDeCompras.<span style="color: #660066;">addItem</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Livro'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> CarrinhoDeCompras.<span style="color: #660066;">addItem</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Caneca'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> CarrinhoDeCompras.<span style="color: #660066;">addItem</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Livro'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">//Opa, o item Livro já está adicionado</span><br /> <br /> CarrinhoDeCompras.<span style="color: #660066;">removeItem</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Livro'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// remove ok</span><br /> CarrinhoDeCompras.<span style="color: #660066;">removeItem</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Livro'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// Opa, não temos o item Livro no carrinho de compras</span><br /> <br /> <span style="color: #006600; font-style: italic;">// mas não poderiámos fazer algo assim:</span><br /> <br /> CarrinhoDeCompras.<span style="color: #660066;">itens</span>.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Camiseta'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div><p>Neste caso, eu estou retornando um objeto contendo a referências das funções que eu declarei dentro da minha função autoexecutável. Perceba que, em hipótese alguma, eu conseguiria acessar diretamente o conteúdo/valor do array itens, pois eu não tenho uma referência dele externamente.</p><p>Isto é algo importante, por dois motivos:</p><ol><li>Se você estiver num time de desenvolvimento e desenvolver um módulo utilizando o module pattern, o desenvolvedor que pegar o seu módulo para utilizar saberá o que ele pode e o que não pode acessar.</li><li>Você previne que aquele engraçadinho que sabe usar o Firebug mexa nos seus objetos em tempo de execução.</li></ol><h3>Onde o jQuery entra nesta história?</h3><p>O jQuery entra principalmente na parte em que começamos a trabalhar com <a href="http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/">eventos customizados</a>. Estes eventos customizados podem funcionar como um meio de comunicação entre os módulos da aplicação, sem que um conheça necessariamente o outro. O que é necessário que cada módulo saiba é como utilizar os eventos.</p><p> Continuando o exemplo anterior:</p><div class="codecolorer-container javascript default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #003366; font-weight: bold;">var</span> CarrinhoDeCompras <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br /> &nbsp; <span style="color: #003366; font-weight: bold;">var</span> itens <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> &nbsp;<span style="color: #006600; font-style: italic;">// variável &quot;privada&quot;. Não pode ser acessada externamente</span><br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> hasItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">return</span> jQuery.<span style="color: #660066;">inArray</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span>itens<span style="color: #009900;">&#41;</span><span style="color: #339933;">!=-</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> addItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>hasItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; itens.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">else</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Opa! O item '</span><span style="color: #339933;">+</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">+</span><span style="color: #3366CC;">' já está selecionado'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> removeItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">var</span> position <span style="color: #339933;">=</span> jQuery.<span style="color: #660066;">inArray</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">,</span>itens<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>hasItem<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">delete</span> itens<span style="color: #009900;">&#91;</span>position<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">else</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Opa, não temos o item '</span><span style="color: #339933;">+</span><span style="color: #000066; font-weight: bold;">item</span><span style="color: #339933;">+</span><span style="color: #3366CC;">' no carrinho de compras'</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> finalizarCompras<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// dispara o evento &quot;finalizaCompras&quot;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// quem estiver &quot;ouvindo&quot; este evento, receberá os itens como argumento</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; $<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">trigger</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;finalizaCompras&quot;</span><span style="color: #339933;">,</span>itens<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span> <span style="color: #006600; font-style: italic;">// algum código de inicialização</span><br /> &nbsp; &nbsp; <br /> &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// retorna um objeto com o que será visível pro mundo</span><br /> &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// note que o array itens não está incluído</span><br /> &nbsp; &nbsp; <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>removeItem<span style="color: #339933;">:</span>removeItem<span style="color: #339933;">,</span>addItem<span style="color: #339933;">:</span>addItem<span style="color: #339933;">,</span>init<span style="color: #339933;">:</span>init<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br /> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> <br /> <br /> <span style="color: #003366; font-weight: bold;">var</span> Services <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp;<br /> &nbsp; &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> finalizarCompras<span style="color: #009900;">&#40;</span>event<span style="color: #339933;">,</span>itens<span style="color: #009900;">&#41;</span> <span style="color: #006600; font-style: italic;">// função &quot;privada&quot;. Não pode ser acessada externamente</span><br /> &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #006600; font-style: italic;">// envia os itens por AJAX e faz algum tratamento.</span><br /> &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp; &nbsp;<span style="color: #003366; font-weight: bold;">function</span> init<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br /> &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// &quot;escuta&quot; pelo evento finalizaCompras</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// quando o mesmo for disparado, a função finalizarCompras será executada</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color: #006600; font-style: italic;">// com os parâmetros do evento</span><br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">bind</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;finalizaCompras&quot;</span><span style="color: #339933;">,</span>finalizarCompras<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp;<span style="color: #009900;">&#125;</span><br /> <br /> &nbsp; &nbsp; &nbsp;<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>init<span style="color: #339933;">:</span>init<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span><br /> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> <br /> <br /> $<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br /> &nbsp; &nbsp; &nbsp;<span style="color: #006600; font-style: italic;">//inicializamos os módulos e colocamos os manipuladores de eventos.</span><br /> &nbsp; &nbsp; &nbsp;CarrinhoDeCompras.<span style="color: #660066;">init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> &nbsp; &nbsp; &nbsp;Services.<span style="color: #660066;">init</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br /> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></div></div><p>Whoa! Conseguimos desacoplar nossa aplicação utilizando <a href="http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/">eventos customizados</a>.</p><p><strong>Um módulo não conhece o outro</strong>, mas os mesmos se comunicam através de eventos. Note que a única coisa comum entre os módulos é o nome do evento utilizado para finalizar a compra.</p><p>Fazendo um paralelo com Programação Orientada a Objetos, os eventos seriam nossa Interface, neste caso.</p><p>Seria possível ainda, o módulo Service disparar um evento para avisar o CarrinhoDeCompras quando a transação for completada.</p><p>Interessante, não? <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /></p><p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento básico de eventos'>[jQuery para apressados] Tratamento básico de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-entendendo-seletores/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Entendendo seletores'>[jQuery para apressados] &#8211; Entendendo seletores</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Trabalhando com eventos customizados'>[jQuery para apressados] &#8211; Trabalhando com eventos customizados</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-modularizando-sua-aplicacao-com-module-pattern-e-jquery/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>[jQuery para apressados] Efeitos e animações avançadas</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-avancadas/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-efeitos-e-animacoes-avancadas</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-avancadas/#comments</comments> <pubDate>Wed, 21 Jul 2010 10:42:24 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=636</guid> <description><![CDATA[No post anterior, eu mostrei alguns efeitos e animações básicas que o jQuery oferece. Neste post eu vou mostrar algumas outras funcionalidades mais avançadas. Encadeando efeitos Os métodos de efeitos do jQuery permitem que você passe uma função de callback como argumento para serem executados assim que os efeito termine. Esta funcionalidade nos permite encadear [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-efeitos-e-animacoes-avancadas%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-efeitos-e-animacoes-avancadas%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>No <a href="http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/">post anterior</a>, eu mostrei alguns efeitos e animações básicas que o jQuery oferece. Neste post eu vou mostrar algumas outras funcionalidades mais avançadas.<h3>Encadeando efeitos</h3>Os métodos de efeitos do jQuery permitem que você passe uma função de callback como argumento para serem executados assim que os efeito termine. Esta funcionalidade nos permite encadear efeitos:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; &nbsp; $('a').slideUp(1000,function() { &nbsp;$(this).slideDown(1000) });<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div><p></p><p><button name="testarEncadeamento1">Testar encadeamento de efeitos nesta página! </button></p>Você não precisa especificar o tempo de duração do evento: basta passar a função de callback para que a mesma seja executada ao final do evento. Esta estratégia funciona para os métodos $.hide, $.show, $.slideUp, $.slideDown, $.slideToggle, $.fadeIn,$.fadeOut e $.fadeToggle.<h3> Animações customizadas com o $.animate</h3>O jQuery faz as animações customizadas através das propriedades que você quer que ele anime, de uma duração (opcional), de uma função de animação (já pré-definida no jquery - opcional) e de um callback (também opcional) para ser executado quando a animação acabar. Um exemplo bem básico do .animate:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; &nbsp; $('a').animate({'font-size':'15px'});<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div><p></p><p><button name="testarAnimate">Testar $.animate! </button></p>O animate permite que você especifique a duração da animação e permite que você passe N propriedades para se animar:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; &nbsp; $('a').animate({'font-size':'15px','opacity':'0.4'},2000);<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Como funções de 'easing', você pode utilizar as funções 'linear' e a 'swing', que são funções básicas. Alguns plugins, como o <a href="http://jqueryui.com">jQuery UI</a>, permitem a animação de propriedades como a cor da fonte e outras funções de animação.O método $.animate é deveras complexo. Dê uma olhada na<a href="http://api.jquery.com/animate/">documentação oficial</a> se você precisar de algo a mais.See ya!
[inline][/inline]<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Efeitos e animações básicas'>[jQuery para apressados] Efeitos e animações básicas</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Iniciando com jQuery'>[jQuery para apressados] &#8211; Iniciando com jQuery</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-entendendo-seletores/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Entendendo seletores'>[jQuery para apressados] &#8211; Entendendo seletores</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-avancadas/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>[jQuery para apressados] Efeitos e animações básicas</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-efeitos-e-animacoes-basicas</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/#comments</comments> <pubDate>Tue, 20 Jul 2010 10:44:25 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=631</guid> <description><![CDATA[Apesar do jQuery ter uma enorme lista de plugins para efeitos, ele possui um framework básico de eventos que serve para 80-90% dos casos que eu vejo. Métodos básicos Os métodos básicos escondem e mostram elementos utilizando alguns efeitos. Dê uma olhada no método hide e no show: &#60;script src=&#34;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&#34; type=&#34;text/javascript&#34;&#62;&#60;/script&#62; &#60;script type=&#34;text/javascript&#34;&#62; $(document).ready(function(){ &#160; [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-efeitos-e-animacoes-basicas%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-efeitos-e-animacoes-basicas%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>Apesar do jQuery ter uma enorme lista de plugins para efeitos, ele possui um framework básico de eventos que serve para 80-90% dos casos que eu vejo.<h3>Métodos básicos</h3>Os métodos básicos escondem e mostram elementos utilizando alguns efeitos. Dê uma olhada no método hide e no show:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; &nbsp; $('a').hover(function(){ $(this).hide(1000) })<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.mouseout(function(){ $(this).show(1000) } );<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>O que eu faço no código acima é aplicar duas funções, uma para quando o mouse estiver sobre um link (elemento 'a') e outra para quando o mouse sair de cima. Nas duas eu coloco a função hide e show com um argumento que diz pro jQuery quanto tempo que a animação deve durar.<p> <button name="executeHideShow">Aplicar hide e show nos links!</button> <button name="remove">Remover hide e show nos links!</button></p><strong>Nota</strong>: estes métodos são "sobrecarregados". Se você não passar nenhum valor como argumento, o elemento será mostrado/escondido sem animações.<h3>slideDown e slideUp</h3>Esconde e mostra (respectivamente) elementos utilizando o efeito slide. O uso é simples:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; &nbsp; $('a').hover(function(){ $(this).slideUp() })<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.mouseout(function(){ $(this).slideDown() } );<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Estes métodos também aceitam um argumento numérico que especifica a duração do evento.<p> <button name="executeHideSlide">Aplicar slideUp e slideDown nos links!</button> <button name="remove">Remover slideUp e slideDown nos links!</button></p><h3>fadeOut e fadeIn</h3>Esconde e mostra (respectivamente) elementos ajustando a sua transparência até desaparecerem/aparecerem por completo. O uso é bem simples também:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; &nbsp; $('a').hover(function(){ $(this).fadeOut() })<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.mouseout(function(){ $(this).fadeIn() } );<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Assim como o slideUp e slideDown, eles também suportam um argumento numérico que especifica a duração do evento.<p> <button name="executeHide">Aplicar fadeIn e fadeOut nos links!</button> <button name="remove">Remover fadeIn e fadeOut nos links!</button></p><h3> Os métodos toggle</h3>O toggle é um utilitário do jQuery que lhe permite mostrar/esconder elementos sem consultar se o mesmo está visível ou não. Ou seja, ao invés de fazer algo assim:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> <br /> &nbsp; &nbsp; &nbsp; $('h1').hover(function(){ <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if( $('p:visible').length == 0) //nenhum p visível<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$('p').show()<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$('p').hide()<br /> &nbsp; &nbsp; &nbsp; &nbsp;});<br /> <br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Você pode fazer algo assim:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> <br /> &nbsp; &nbsp; &nbsp; $('h1').hover(function(){ <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;$('p').toggle();<br /> &nbsp; &nbsp; &nbsp; &nbsp;});<br /> <br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>O mais interessante é que os outros métodos de efeitos possuem uma 'versão toggle': slideToggle, fadeToggle. Estes eu deixo pra você testar <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />No próximo post eu vou falar sobre callbacks de efeitos, encadeamento de efeitos e efeitos avançados. See ya![inline][/inline]<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-avancadas/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Efeitos e animações avançadas'>[jQuery para apressados] Efeitos e animações avançadas</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-entendendo-seletores/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Entendendo seletores'>[jQuery para apressados] &#8211; Entendendo seletores</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Iniciando com jQuery'>[jQuery para apressados] &#8211; Iniciando com jQuery</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>[jQuery para apressados] &#8211; Trabalhando com eventos customizados</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-trabalhando-com-eventos-customizados</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/#comments</comments> <pubDate>Mon, 19 Jul 2010 09:15:49 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=619</guid> <description><![CDATA[Eventos customizados em JavaScript podem trazer algumas possibilidades legais: imagine que você tenha uma grande aplicação em JavaScript dividida em módulos. Você pode diminuir o acoplamento entre eles utilizando eventos customizados para comunicação inter-módulos. Neste post, eu vou mostrar como você pode aproveitar as facilidades do jQuery para uso de eventos customizados Let's pull the [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-trabalhando-com-eventos-customizados%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-trabalhando-com-eventos-customizados%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>Eventos customizados em JavaScript podem trazer algumas possibilidades legais: imagine que você tenha uma grande aplicação em JavaScript dividida em módulos. Você pode diminuir o acoplamento entre eles utilizando eventos customizados para comunicação inter-módulos. Neste post, eu vou mostrar como você pode aproveitar as facilidades do jQuery para uso de eventos customizados<h3>Let's pull the $.trigger</h3>O método trigger serve para lançar eventos e toma como parâmetro o nome do evento. Por exemplo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; $('form input[type=submit]').trigger('click');<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>O que isto vai fazer terá o mesmo efeito de um usuário clicando em todos os botões de submit de todos os formulários do documento: basicamente, irá disparar o evento "click" para todos os botões submit dos formulários.Você pode lançar os eventos padrões do jQuery somente chamando os métodos de atalho sem argumentos, por exemplo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; <br /> &nbsp; &nbsp;// mesma coisa de $('form input[type=submit]').trigger('click');<br /> &nbsp; &nbsp;$('form input[type=submit]').click();<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Você ainda pode passar argumentos customizados para a função manipuladora do evento, como neste exemplo adaptado da documentação oficial do jQuery:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> &nbsp; &nbsp; $('button[name=executeEvent]').bind('custom', function(event, param1, param2) {<br /> &nbsp; &nbsp; &nbsp; alert(param1 + &quot;\n&quot; + param2);<br /> &nbsp; &nbsp; });<br /> <br /> &nbsp; &nbsp; $('button[name=executeEvent]').trigger('custom', ['Evento', 'Customizado']);<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div><p><button name="executeEvent" value="Testar evento customizado!" >Testar evento customizado!</button></p>Neste caso, já estamos fazendo uso de um evento customizado: você pode passar qualquer string como argumento do trigger e do bind e voilà, você tem um evento customizado! Vale notar que, o jQuery não possui métodos de atalho (como o $.click()) para eventos customizados, mas nada impede que você mesmo os crie.<p><strong>Nota</strong>: No exemplo do botão acima, eu tive que colocar um bind para o evento click e dentro do evento click eu disparo o evento 'custom'. Isso não afeta o comportamento do evento customizado, apenas fiz assim para poder demonstrar melhor.</p>No próximo post farei uma introdução ao module pattern e mostrarei como você pode desacoplar sua aplicação JavaScript usando custom events. Até mais![inline][/inline]<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento básico de eventos'>[jQuery para apressados] Tratamento básico de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-avancado-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento avançado de eventos'>[jQuery para apressados] Tratamento avançado de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Iniciando com jQuery'>[jQuery para apressados] &#8211; Iniciando com jQuery</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>[jQuery para apressados] Tratamento avançado de eventos</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-avancado-de-eventos/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-tratamento-avancado-de-eventos</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-avancado-de-eventos/#comments</comments> <pubDate>Sat, 17 Jul 2010 10:44:31 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=614</guid> <description><![CDATA[No post anterior eu expliquei como funciona o tratamento de eventos básicos no jQuery. Neste post eu vou passar uma explicação mais aprofundada sobre o assunto. $.live and let $.die Os métodos 'live' e 'die' funcionam exatamente da mesma forma dos métodos bind e unbind exceto por uma característica: eles podem trabalhar com elementos inseridos [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-tratamento-avancado-de-eventos%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-tratamento-avancado-de-eventos%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>No <a href="http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/">post anterior</a> eu expliquei como funciona o tratamento de eventos básicos no jQuery. Neste post eu vou passar uma explicação mais aprofundada sobre o assunto.<h3> $.live and let $.die</h3>Os métodos 'live' e 'die' funcionam exatamente da mesma forma dos métodos bind e unbind exceto por uma característica: eles podem trabalhar com elementos inseridos dinamicamente na página. Exemplo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function(){<br /> <br /> &nbsp; &nbsp; &nbsp;$('h1').bind('click',function(){ alert('fui clicado') }); // só funciona para os atuais elementos da página<br /> &nbsp; &nbsp; &nbsp;$('h1').live('click',function(){ alert('fui clicado -- live') }); // funciona para os elementos atuais<br /> <br /> &nbsp; &nbsp; //vai exibir o alert &quot;fui clicado -- live&quot; quando<br /> &nbsp; &nbsp; // for clicado <br /> &nbsp; &nbsp; $('body').append('<span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/h1.html"><span style="color: #000000; font-weight: bold;">h1</span></a>&gt;</span>Elemento inserido dinamicamente<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/h1.html"><span style="color: #000000; font-weight: bold;">h1</span></a>&gt;</span>'); <br /> &nbsp; &nbsp; <br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Estes métodos são especialmente úteis quando se trabalha com AJAX, pois com AJAX torna-se muito comum inserir e remover itens do documento dinamicamente.<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> clickHandler = function()<br /> {<br /> &nbsp; &nbsp;alert('Fui clicado e não serei clicado novamente');<br /> &nbsp; &nbsp;$(this).die('click',clickHandler);<br /> }<br /> <br /> $(document).ready(function(){<br /> <br /> &nbsp; &nbsp; &nbsp;$('h1').bind('click',function(){ alert('fui clicado') }); // só funciona para os atuais elementos da página<br /> &nbsp; &nbsp; &nbsp;$('h1').live('click',clickHandler); // funciona para os elementos atuais<br /> <br /> &nbsp; &nbsp; $('body').append('<span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/h1.html"><span style="color: #000000; font-weight: bold;">h1</span></a>&gt;</span>Elemento inserido dinamicamente<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/h1.html"><span style="color: #000000; font-weight: bold;">h1</span></a>&gt;</span>'); <br /> &nbsp; &nbsp; <br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div><h3>$.delegate e $.undelegate</h3>Os métodos delegate e undelegate são métodos auxiliares dos métodos live e die. Eles trabalham com elementos atuais e do futuro (quando os mesmos forem inseridos) e permitem adicionar manipuladores de eventos em elementos DOM específicos. Exemplo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> // retirado da documentação do jQuery<br /> $(document).ready(function(){<br /> <br /> &nbsp; &nbsp; $(&quot;table&quot;).delegate(&quot;td&quot;, &quot;hover&quot;, function(){<br /> &nbsp; &nbsp; &nbsp; &nbsp; $(this).toggleClass(&quot;hover&quot;);<br /> &nbsp; &nbsp; });<br /> <br /> &nbsp; &nbsp; // o código acima seria equivalente a este:<br /> &nbsp; &nbsp;$(&quot;table&quot;).each(function(){<br /> &nbsp; &nbsp; $(&quot;td&quot;, this).live(&quot;hover&quot;, function(){<br /> &nbsp; &nbsp; &nbsp; &nbsp; $(this).toggleClass(&quot;hover&quot;);<br /> &nbsp; &nbsp; });<br /> &nbsp; &nbsp;});<br /> <br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div><strong>Nota</strong>: Dependendo do seletor, o jQuery pode retornar um elemento ou um array de elementos. O método 'each' utilizado acima aplica a função passada por argumento pra ele para cada elemento do array retornado pelo seletor do jQuery neste caso. Para maiores detalhes do each, não deixe de ver <a href="http://api.jquery.com/jQuery.each/">a documentação</a>.<h3> O objeto event</h3>No <a href="http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/">post anterior</a>, eu mostrei um pequeno exemplo (sem dar muitos comentários) sobre o objeto event:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> enviarDados = function(event)<br /> {<br /> &nbsp; &nbsp; var dados = event.data;<br /> &nbsp; &nbsp; alert('Enviando dados. Dados enviados:'+dados);<br /> }<br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').bind('click','Dado que vai para a função que trata o evento',enviarDados);<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Reparem o argumento "event" da função enviarDados. Este objeto contém vários detalhes sobre o evento, incluindo o elemento, informações sobre a propagação do evento, posição X e Y do mouse onde aconteceu o evento o tipo do evento e muito mais. Para ver a documentação completa de todos estes atributos, veja a <a href="http://api.jquery.com/category/events/">documentação oficial do jQuery</a>No próximo post eu falarei como você pode criar seus próprios eventos e como isto pode lhe ajudar a separar melhor sua aplicação, caso ela cresça muito.Até mais!<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento básico de eventos'>[jQuery para apressados] Tratamento básico de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Trabalhando com eventos customizados'>[jQuery para apressados] &#8211; Trabalhando com eventos customizados</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Efeitos e animações básicas'>[jQuery para apressados] Efeitos e animações básicas</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-avancado-de-eventos/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>[jQuery para apressados] Tratamento básico de eventos</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-tratamento-basico-de-eventos</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/#comments</comments> <pubDate>Fri, 16 Jul 2010 09:45:25 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=610</guid> <description><![CDATA[Um evento é uma ação que geralmente é iniciada fora do escopo de um programa e que é manipulado por uma parte do códigod dentro do programa [Wikipedia]. Um evento pode ser o clique do usuário de um botão, o pressionar de uma tecla do teclado ou uma resposta de uma requisição do servidor. Dê [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-tratamento-basico-de-eventos%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-tratamento-basico-de-eventos%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>Um evento é uma ação que geralmente é iniciada fora do escopo de um programa e que é manipulado por uma parte do códigod dentro do programa [<a href="http://en.wikipedia.org/wiki/Event_(computing)">Wikipedia</a>]. Um evento pode ser o clique do usuário de um botão, o pressionar de uma tecla do teclado ou uma resposta de uma requisição do servidor.Dê uma olhada como você pode manipular um clique a um botão:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').click(function()<br /> &nbsp; &nbsp; &nbsp;{<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert('Enviando dados...');<br /> &nbsp; &nbsp; &nbsp;});<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>O que você basicamente faz aí em cima é dizer pro jQuery: execute esta função que eu estou passando como argumento do método click quando o(s) elemento(s) que atendem ao seletor #enviarDados for clicado.Naturalmente, você pode separar um pouco mais as coisas:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> enviarDados = function()<br /> {<br /> &nbsp; &nbsp; alert('Enviando dados');<br /> }<br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').click(enviarDados);<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Além do click, o jQuery tem muitos outros métodos para tratamento de evento. Dentre eles se destacam:<ul><li>hover - quando o mouse for passado sobre o elemento</li><li>blur - quando o elemento perder o foco</li><li>focus - quando o elemento de formulário ou link ganhar foco</li><li>change - quando um elemento de formulário for mudado</li><li>mousedown - quando clicarem (sem necessariamente "soltar" o mouse) sobre o elemento</li><li>mouseup - quando "soltarem" o mouse depois de clicado no elemento</li><li><a href="http://api.jquery.com/category/events/">E muitos outros</a></li></ul><h3> Usando o bind</h3>Todos os métodos acima descritos são métodos "atalho" e todos eles utilizam o método bind para mapear eventos. Ele possui uma argumento extra que eu gosto de utilizar de vez em quando: a passagem de dados para o tratador do evento. Exemplo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> enviarDados = function(event)<br /> {<br /> &nbsp; &nbsp; var dados = event.data;<br /> &nbsp; &nbsp; alert('Enviando dados. Dados enviados:'+dados);<br /> }<br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').bind('click','Dado que vai para a função que trata o evento',enviarDados);<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>De vez em quando, precisamos remover tratadores de eventos de alguns elementos. Isso é feito com o método unbind:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> enviarDados = function(event)<br /> {<br /> &nbsp; &nbsp; var dados = event.data;<br /> &nbsp; &nbsp; alert('Enviando dados. Dados enviados:'+dados);<br /> &nbsp; &nbsp; $(this).unbind('click');<br /> }<br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').bind('click','Dado que vai para a função que trata o evento',enviarDados);<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Note a palavra chave this na função que trata o evento: neste contexto, ela simboliza o elemento que sofreu o evento (no nosso caso, o elemento que contém o id="enviarDados")O que eu fiz acima foi remover o tratamento do evento 'click' para o elemento que foi clicado. Neste caso, o tratamento deste evento irá acontecer somente uma vez. Se eu chamasse o método unbind sem nenhum argumento, eu removeria todos os eventos atrelados a ele:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> enviarDados = function(event)<br /> {<br /> &nbsp; &nbsp; var dados = event.data;<br /> &nbsp; &nbsp; alert('Enviando dados. Dados enviados:'+dados);<br /> &nbsp; &nbsp; $(this).unbind(); //remove todos os eventos<br /> }<br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').bind('click','Dado que vai para a função que trata o evento',enviarDados);<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Você ainda pode remover somente uma das funções que tratam um determinado evento. Suponhamos que você, por qualquer motivo, tenha mais de uma função tratando o mesmo evento no mesmo elemento e quer remover somente uma função: há um terceiro argumento no unbind que permite remover somente uma função:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> enviarDados = function(event)<br /> {<br /> &nbsp; &nbsp; var dados = event.data;<br /> &nbsp; &nbsp; alert('Enviando dados. Dados enviados:'+dados);<br /> &nbsp; &nbsp; $(this).unbind('click',enviarDados); // remove o tratamento do evento click pela função<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // enviarDados<br /> }<br /> <br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp; &nbsp;$('#enviarDados').bind('click','Dado que vai para a função que trata o evento',enviarDados);<br /> });<br /> <br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Legal, né? <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />Amanhã falarei sobre tratamento avançado de eventos e eventos customizados. See ya!<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-avancado-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento avançado de eventos'>[jQuery para apressados] Tratamento avançado de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Trabalhando com eventos customizados'>[jQuery para apressados] &#8211; Trabalhando com eventos customizados</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Iniciando com jQuery'>[jQuery para apressados] &#8211; Iniciando com jQuery</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>[jQuery para apressados] &#8211; Entendendo seletores</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-entendendo-seletores/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-entendendo-seletores</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-entendendo-seletores/#comments</comments> <pubDate>Thu, 15 Jul 2010 11:11:35 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=585</guid> <description><![CDATA[Uma das especialidades do jQuery é selecionar um conjunto de elementos e aplicar algum dos seu métodos sobre eles. "Seletores" são formas de você selecionar um ou mais elementos dentro do seu documento HTML com o intuito de aplicar algum método do jQuery sobre ele. Por exemplo: &#60;script src=&#34;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&#34; type=&#34;text/javascript&#34;&#62;&#60;/script&#62; &#60;script type=&#34;text/javascript&#34;&#62; $(document).ready(function) { &#160; [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-entendendo-seletores%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-entendendo-seletores%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>Uma das especialidades do jQuery é selecionar um conjunto de elementos e aplicar algum dos seu métodos sobre eles. "Seletores" são formas de você selecionar um ou mais elementos dentro do seu documento HTML com o intuito de aplicar algum método do jQuery sobre ele. Por exemplo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> $(document).ready(function)<br /> {<br /> &nbsp; &nbsp; $('a').hide(); //seleciona todos os links e os esconde<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>O código acima é fictício, mas seve para ilustrar. No jQuery, 90% (ou mais) do que você faz o tempo inteiro é selecionar um elemento e fazer alguma coisa com ele.Os seletores do jQuery são bem poderosos. Dê uma olhada nestes exemplos:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> <br /> $(document).ready(function)<br /> {<br /> &nbsp; &nbsp; $('table a').hide(); //seleciona todos os links dentro de tabelas e os esconde<br /> &nbsp; &nbsp; <br /> &nbsp; &nbsp; $('input[name=email]').val(''); //seleciona todos os inputs que tenham a <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//propriedade name=email e apaga seus respectivos conteúdos<br /> &nbsp; &nbsp; <br /> &nbsp; &nbsp; $('#content').show(); //seleciona o elemento com o id content e o exibe<br /> &nbsp; &nbsp; $('div.item').remove(); //seleciona todas as divs que possuem a classe item e as remove<br /> &nbsp; &nbsp; $('.item').remove(); //seleciona todos os elementos com a classe item e os remove<br /> &nbsp; &nbsp; <br /> &nbsp; &nbsp; $('.item:first').slideUp(); //seleciona o primeiro elemento com a classe <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //item e aplica uma animação para faze-lo desaparecer<br /> &nbsp; &nbsp; <br /> &nbsp; &nbsp; $('div:eq(5) a.marcado[rel^=bookmark]').slideDown(); // seleciona todos os links<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// em que o atributo rel que comecem com bookmark e que tenham <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// a classe marcado e que estejam dentro da quinta div dentro do <br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//documento e aplica uma animação para o(s) link(s) aparecer(em)<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Como mostrado acima, você pode selecionar elementos pela sua tag, classe, id, propriedade e posição. Achou poderoso? Espere só até ver a <a href="http://api.jquery.com/category/selectors/">documentação oficial de todos os seletores do jQuery!</a> <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><h3>Live example! Teste aqui mesmo alguns seletores!</h3><p>$<input type="text" name="selector" value="a"/>.slideUp(); <button name="executeSelector" value="Testar!"/>Testar!</p><p>$<input type="text" name="selector2" value="a"/>.slideDown(); <button name="executeSelector2" value="Testar!"/>Testar!</p><p>$<input type="text" name="selector3" value="input"/>.val(''); <button name="executeSelector3" value="Testar!">Testar!</button></p>[inline][/inline]<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Iniciando com jQuery'>[jQuery para apressados] &#8211; Iniciando com jQuery</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento básico de eventos'>[jQuery para apressados] Tratamento básico de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-basicas/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Efeitos e animações básicas'>[jQuery para apressados] Efeitos e animações básicas</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-entendendo-seletores/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>[jQuery para apressados] &#8211; Iniciando com jQuery</title><link>http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=jquery-para-apressados-iniciando-com-jquery</link> <comments>http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/#comments</comments> <pubDate>Wed, 14 Jul 2010 14:20:59 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[jQuery Para Apressados]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=576</guid> <description><![CDATA[Como minha monografia está me apertando agora, eu pretendo fazer uma série de posts (curtos, frequentes e regulares) sobre dicas simples para jQuery. Partindo do início, este é um post de nível básico se trata de como se iniciar com jQuery. Pra ajudar, eu vou dedicar um pomodoro para cada post O que é jQuery? [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-iniciando-com-jquery%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F07%2Fjquery-para-apressados-iniciando-com-jquery%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>Como minha monografia está me apertando agora, eu pretendo fazer uma série de posts (curtos, frequentes e regulares) sobre dicas simples para jQuery. Partindo do início, este é um post de nível <strong>básico</strong> se trata de como se iniciar com jQuery. Pra ajudar, eu vou dedicar um <a href="http://herberthamaral.com/2009/12/foco-e-produtividade-a-tecnica-do-pomodoro/">pomodoro</a> para cada post <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /><h3>O que é jQuery?</h3> jQuery é basicamente uma biblioteca JavaScript que torna o desenvolvimento para JavaScript mais fácil, produtivo e divertido. Ele contém vários métodos úteis para, principalmente, manipulação de elementos , ajax e eventos. A página inicial é a <a href="http://jquery.com/">http://jquery.com/</a><h3>Hello jQuery!</h3> Primeiro, você precisa inserir o jQuery no seu HTML. Coloque o código abaixo antes do &lt;/body&gt;:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Estamos inserindo o jQuery diretamente do CDN do Google, na versão 1.4.2. Você pode colocar qualquer versão do jQuery no seu código, basta trocar a parte  "1.4.2" do caminho por um novo número de versão.  Feito isso, você pode fazer o nosso Hello World com jQuery (note que eu estou colocando o código depois que eu adicionei o jQuery na página):<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp;<span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span><br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> $(document).ready(function()<br /> {<br /> &nbsp; &nbsp;alert('Hello, world!');<br /> });<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Simples, não? O que acabou de ser feito foi um simples seleção ($(document)) e aplicação do evento 'ready'. Como argumento para o método ready, passamos uma função que vai servir para fazer o tratamento do evento ready, ou seja, a função que será executada quando o documento for carregado.<h3>Fazendo de outras formas</h3> Se você quiser separar a função de callback (esta função que você passa como argumento para o ready), você ainda pode fazer desta forma:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span> <br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> minhaFuncao = function()<br /> {<br /> &nbsp; &nbsp;alert('Hello, world!');<br /> }<br /> <br /> $(document).ready(minhaFuncao);<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>Se você tiver algum problema com o $, há a possibilidade de utilizar a função jQuery para substitui-lo:<div class="codecolorer-container html4strict default" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">src</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js&quot;</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span> <br /> <span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text/javascript&quot;</span>&gt;</span><br /> minhaFuncao = function()<br /> {<br /> &nbsp; &nbsp;alert('Hello, world!');<br /> }<br /> <br /> jQuery(document).ready(minhaFuncao);<br /> <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><a href="http://december.com/html/4/element/script.html"><span style="color: #000000; font-weight: bold;">script</span></a>&gt;</span></div></div>No próximo post eu falarei um pouco sobre seletores. Até mais!<p><h4>Posts relacionados:</h4><ol><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-efeitos-e-animacoes-avancadas/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Efeitos e animações avançadas'>[jQuery para apressados] Efeitos e animações avançadas</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-tratamento-basico-de-eventos/' rel='bookmark' title='Permanent Link: [jQuery para apressados] Tratamento básico de eventos'>[jQuery para apressados] Tratamento básico de eventos</a></li><li><a href='http://herberthamaral.com/2010/07/jquery-para-apressados-trabalhando-com-eventos-customizados/' rel='bookmark' title='Permanent Link: [jQuery para apressados] &#8211; Trabalhando com eventos customizados'>[jQuery para apressados] &#8211; Trabalhando com eventos customizados</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/07/jquery-para-apressados-iniciando-com-jquery/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>[Atualizado] Tradução do Livro jQuery Fundamentals &#8211; Ajude você também!</title><link>http://herberthamaral.com/2010/06/traducao-do-livro-jquery-fundamentals-ajude-voce-tambem/?utm_source=rss&amp;utm_medium=rss&amp;utm_campaign=traducao-do-livro-jquery-fundamentals-ajude-voce-tambem</link> <comments>http://herberthamaral.com/2010/06/traducao-do-livro-jquery-fundamentals-ajude-voce-tambem/#comments</comments> <pubDate>Wed, 23 Jun 2010 11:11:15 +0000</pubDate> <dc:creator>Herberth Amaral</dc:creator> <category><![CDATA[Cursos]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[News]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[opensource]]></category><guid isPermaLink="false">http://herberthamaral.com/?p=546</guid> <description><![CDATA[Depois de um jejum do meu blog eu volto a postar com algumas novidades bacanas: o Elvis Guimarães e eu estamos traduzindo o livro jQuery Fundamentals para pt-BR. Além de contribuir com o conhecimento Open Source, meu objetivo é incentivar o uso deste material nas minhas aulas de jQuery e dar uma mãozinha em quem [...]]]></description> <content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;"> <a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F06%2Ftraducao-do-livro-jquery-fundamentals-ajude-voce-tambem%2F"> <img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fherberthamaral.com%2F2010%2F06%2Ftraducao-do-livro-jquery-fundamentals-ajude-voce-tambem%2F&amp;source=HerberthAmaral&amp;style=normal" height="61" width="50" /> </a></div>Depois de um jejum do meu blog eu volto a postar com algumas novidades bacanas: o <a href="http://twitter.com/elvisgs" target="_blank">Elvis Guimarães</a> e eu estamos traduzindo o livro <a href="http://www.rebeccamurphey.com/jqfundamentals/" target="_blank"> jQuery Fundamentals</a> para pt-BR.Além de contribuir com o conhecimento Open Source, meu objetivo é incentivar o uso deste material nas minhas aulas de jQuery e dar uma mãozinha em quem está começando com JavaScript/jQuery/front-end development.O repositório está disponível em <a href="http://github.com/herberthamaral/jqfundamentals">http://github.com/herberthamaral/jqfundamentals</a>. Estou aguardando seu fork <img src='http://herberthamaral.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />P.S: Se você não sabe como o Git e o GitHub funcionam, eu recomendo a leitura do <a href="http://akitaonrails.com/2008/04/02/micro-tutorial-de-git" target="_blank">Micro tutorial de Git</a> do <a href="http://akitaonrails.com">Fabio Akita</a> Há <a href="http://akitaonrails.com/2008/09/21/colaborando-no-github" target="_blank">um vídeo</a> dele também ensinando como colaborar num projeto no GitHub.P.P.S: O Diego Caxito <a href="http://diegocaxito.wordpress.com/2010/06/29/ajudando-a-traduzir-jquery-fundamentals-para-pt-br/" target="_blank">escreveu um post</a> sobre a 0º versão do evento.<p>Sem posts relacionados.</p>]]></content:encoded> <wfw:commentRss>http://herberthamaral.com/2010/06/traducao-do-livro-jquery-fundamentals-ajude-voce-tambem/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> </channel> </rss>