<?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>Şimşek Mert &#187; Web Programlama</title>
	<atom:link href="http://www.simsekmert.com/wp/category/web-programlama/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.simsekmert.com/wp</link>
	<description>Kişisel Web Sayfası</description>
	<lastBuildDate>Thu, 13 Jan 2011 09:10:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ext JS Javascript Framework</title>
		<link>http://www.simsekmert.com/wp/2011/01/ext-js-javascript-framework/</link>
		<comments>http://www.simsekmert.com/wp/2011/01/ext-js-javascript-framework/#comments</comments>
		<pubDate>Sun, 02 Jan 2011 21:22:38 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[Ext JS]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Web Programlama]]></category>
		<category><![CDATA[ext]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[sencha]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=139</guid>
		<description><![CDATA[Bu bölümde, bir çok önemli özelliği ile ön plana çıkan ve benzer kütüphanelere göre çok daha kabiliyetli olan ve kullanıcı arayüzü açısından oldukça başarılı bir javascript çatısı olan Ext JS den ve özelliklerinden bahsedeceğim.

1.Bölüm
Gerekli dosyalar

Ext JS Kütüphanesi : Öncelikle http://www.sencha.com/products/js/download.php adresinden Ext JS kütüphanesinin en son sürümünü indirim. Ben bu yazıyı yazarken Ext JS nin [...]]]></description>
			<content:encoded><![CDATA[<p>Bu bölümde, bir çok önemli özelliği ile ön plana çıkan ve benzer kütüphanelere göre çok daha kabiliyetli olan ve kullanıcı arayüzü açısından oldukça başarılı bir javascript çatısı olan Ext JS den ve özelliklerinden bahsedeceğim.</p>
<p><span id="more-139"></span></p>
<h1>1.Bölüm</h1>
<h3>Gerekli dosyalar</h3>
<ul>
<li style="text-align: justify;"><strong>Ext JS Kütüphanesi :</strong> Öncelikle <a href="http://www.sencha.com/products/js/download.php">http://www.sencha.com/products/js/download.php</a> adresinden Ext JS kütüphanesinin en son sürümünü indirim. Ben bu yazıyı yazarken Ext JS nin indirilebilir en son sürümü 3.3.1 idi. Bu nedenle yazımızın devamında 3.3.1 diye bahsettiğimiz bölüm siz yeni bir sürüm ile çalışıyorsanız değişecektir.</li>
<li style="text-align: justify;"><strong>Web Sunucusu :</strong> Ext JS kütüphanesi, istemci tarafında çalışan javascript dosyalarından oluştuğu için html dosyalar ile herhangi bir web sunucusu olmadan da tarayıcılar tarafından çalıştırılabilir. Fakat biz çalışmamıza bir web sunucusu ile devam edeceğiz. Windows üzerinde çalışıyorsanız windows işletim sistemlerine Apache Web Sunucusu, MySQL veritabanı sunucusu ve PHP web programlama dili desteğini otomatik olarak kuran bir kaç paket bulunmaktadır. Bunlardan ikisini aşağıda belirttim. Bunlardan birini kullanarak web sunucunuzu yapılandırabilirsiniz.
<ul>
<li style="text-align: justify;">AppServNetwork -&gt; <a href="http://www.appservnetwork.com">http://www.appservnetwork.com</a></li>
<li>WampServer -&gt; <a href="http://www.wampserver.com">http://www.wampserver.com</a></li>
</ul>
</li>
</ul>
<h3>Kurulum</h3>
<p>Web sunucunuzu kurduysanız web sunucusu kurulum sırasında belirttiğiniz adresin içine www klasörü oluşturmuştur. Bu klasörün içine örnek uygulamamız için myApp isimli bir klasör oluşturalım. Bu klasör içine indirdiğimiz Ext JS kütüphanesini kopyalayalım.</p>
<p>myApp klasörünün içine geliştireceğimiz uygulamalara ait dosyaları tutmak için application adında bir klasör daha oluşturalım.</p>
<p><img class="alignnone size-full wp-image-156" title="1" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/1.PNG" alt="1" width="544" height="175" /></p>
<p>Şimdi ext-3.3.1 klasörünün içindeki dosya ve klasörleri inceleyelim.</p>
<p><img class="alignnone size-full wp-image-157" title="2" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/2.png" alt="2" width="540" height="188" /></p>
<ul>
<li style="text-align: justify;"><strong>adapter</strong> klasörü, prototype, jQuery, YUI and Ext JS gibi klasörlerin bulunduğu bir klasördür. Bu klasör ve içindekiler ileride daha detaylı incelenecektir.</li>
<li style="text-align: justify;"><strong>resources</strong> klasörü, içerisinde görseller, css dosyaları vs bulunur.</li>
<li style="text-align: justify;"><strong>ext-all.js</strong> dosyası, Ext JS nin bileşenlerinin bulunduğu javascript dosyasıdır.</li>
</ul>
<h3>Testing Ext JS Framework</h3>
<p><img src="file:///C:/Users/simsek/AppData/Local/Temp/moz-screenshot.png" alt="" /></p>
<p>Şimdi ilk html dosyamızı oluşturup ext kütüphanesini yükleyelim. Bunun için üç tane dosyanın &lt;head&gt;&lt;/head&gt; bloğunda çağrılması gerekir.</p>
<ul>
<li>ext-3.3.1/resources/css/ext-all.css</li>
<li>ext-3.3.1/adapter/ext/ext-base.js</li>
<li style="text-align: justify;">ext-3.3.1/ext-all.js</li>
</ul>
<p>Bun göre aşağıdaki html kodlarını sayfamızın &lt;head&gt;&lt;/head&gt; bloğuna  yerleştirelim.</p>
<pre class="js">&lt;link rel="stylesheet" type="text/css" href="../ext-3.3.1/resources/css/ext-all.css" /&gt;

&lt;script type="text/javascript" src="../ext-3.3.1/adapter/ext/ext-base.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="../ext-3.3.1/ext-all.js"&gt;&lt;/script&gt;</pre>
<p style="text-align: justify;">Ext JS kütüphanesini test etmek için kütüphanemizin kullandığı onReady olayına bir dinleyici eklemek yeterlidir. onReady olayı tüm sistem yüklendikten sonra aktif olur. Örneğin, DOM kullanıma hazır hale geldiğinde kullanıcıya &#8220;Hoşgeldiniz.&#8221; diye bir mesaj verelim.</p>
<blockquote>
<p style="text-align: justify;">&lt;script type=&#8221;text/javascript&#8221;&gt;</p>
<p style="text-align: justify; padding-left: 30px;">Ext.onReady(function(){<br />
alert(&#8217;Hoşgeldiniz.&#8217;);<br />
});</p>
<p style="text-align: justify;">&lt;/script&gt;</p>
</blockquote>
<p>Buna göre, first.html olarak application klasörü içine oluşturduğumuz dosyanın içeriği aşağıdaki gibi olmalıdır.</p>
<blockquote>
<p style="text-align: justify;">&lt;!DOCTYPE html PUBLIC &#8220;-//W3C//DTD XHTML 1.0 Strict//EN&#8221; &#8220;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&#8221;&gt;</p>
<p>&lt;html xmlns=&#8221;http://www.w3.org/1999/xhtml&#8221; xml:lang=&#8221;en&#8221;&gt;<br />
&lt;head&gt;<br />
&lt;meta http-equiv=&#8221;Content-Type&#8221; content=&#8221;text/html; charset=UTF-8&#8243; /&gt;<br />
&lt;title&gt;Ext JS Library&lt;/title&gt;</p>
<p>&lt;link rel=&#8221;stylesheet&#8221; type=&#8221;text/css&#8221; href=&#8221;../ext-3.3.1/resources/css/ext-all.css&#8221; /&gt;</p>
<p>&lt;script type=&#8221;text/javascript&#8221; src=&#8221;../ext-3.3.1/adapter/ext/ext-base.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script type=&#8221;text/javascript&#8221; src=&#8221;../ext-3.3.1/ext-all.js&#8221;&gt;&lt;/script&gt;</p>
<p>&lt;script type=&#8221;text/javascript&#8221;&gt;<br />
Ext.onReady(function() {<br />
alert(&#8217;Hosgeldiniz.&#8217;);<br />
});<br />
&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;</p>
<p>&lt;/body&gt;<br />
&lt;/html&gt;</p></blockquote>
<p>Bu dosyayı web tarayıcınız ile çalıştırdığınızda aşağıdaki gibi &#8220;Hoşgeldiniz.&#8221; mesajı verilecektir.</p>
<p><img class="alignnone size-full wp-image-155" title="3" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/3.png" alt="3" width="395" height="155" /></p>
<ul>
<li><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/first.rar">Uygulamayı buradan indirebilirsiniz.</a></li>
<li><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/first.html" target="_blank">Uygulamanın demosunu buradan görebilirsiniz.</a></li>
</ul>
<h1>2.Bölüm</h1>
<p>Bu bölümde yeni bir uygulama ile bir pencere oluşturalım. Pencere oluşturmak için</p>
<blockquote>
<p style="padding-left: 30px;">win = new Ext.Window({<br />
title: &#8216;İlk Pencerem&#8217;, //pencerenin bağlığını belirtir.<br />
width:500, //pencerenin genişliğini belirtir.<br />
height:300,  //pencerenin yüksekliğini belirtir.<br />
minimizable: true,<br />
maximizable: true,<br />
closeAction:&#8217;hide&#8217;,<br />
});</p></blockquote>
<p>kodlarını kullanmamız gerekir. Burada önemli olan new Ext.Window komutu ile yeni bir pencere oluşturmaktır. Diğer seçenekler pencerenin özelliklerini düzenlemeye yarar.</p>
<p>Pencereyi oluşturmak pencereyi göstermek için yeterli değildir. Pencereyi göstermek için ayrıca win.show() fonksiyonunu çağırmamız gerekir.</p>
<p>Bu durumda yeni html sayfamız aşağıdaki gibi olacaktır.</p>
<blockquote><p>&lt;!DOCTYPE html PUBLIC &#8220;-//W3C//DTD XHTML 1.0 Strict//EN&#8221; &#8220;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&#8221;&gt;</p>
<p>&lt;html xmlns=&#8221;http://www.w3.org/1999/xhtml&#8221; xml:lang=&#8221;en&#8221;&gt;<br />
&lt;head&gt;<br />
&lt;meta http-equiv=&#8221;Content-Type&#8221; content=&#8221;text/html; charset=UTF-8&#8243; /&gt;<br />
&lt;title&gt;Ext JS Library &#8211; İkinci Örnek&lt;/title&gt;</p>
<p>&lt;link rel=&#8221;stylesheet&#8221; type=&#8221;text/css&#8221; href=&#8221;../ext-3.3.1/resources/css/ext-all.css&#8221; /&gt;</p>
<p>&lt;script type=&#8221;text/javascript&#8221; src=&#8221;../ext-3.3.1/adapter/ext/ext-base.js&#8221;&gt;&lt;/script&gt;<br />
&lt;script type=&#8221;text/javascript&#8221; src=&#8221;../ext-3.3.1/ext-all.js&#8221;&gt;&lt;/script&gt;</p>
<p>&lt;script type=&#8221;text/javascript&#8221;&gt;<br />
Ext.onReady(function() {<br />
win = new Ext.Window({<br />
title: &#8216;İlk Pencerem&#8217;, //pencerenin bağlığını gösterir<br />
width:500,<br />
height:300,<br />
minimizable: true,<br />
maximizable: true,<br />
closeAction:&#8217;hide&#8217;,<br />
});<br />
win.show();<br />
});<br />
&lt;/script&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;</p>
<p>&lt;/body&gt;<br />
&lt;/html&gt;</p></blockquote>
<p>Bu sayfayı ben second.html olarak kaydedip çalıştıdığımda aşağıdaki gibi bir görüntü oluştu.</p>
<p><img class="alignnone size-full wp-image-162" title="4" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/4.PNG" alt="4" width="568" height="365" /></p>
<ul>
<li><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second.rar">Uygulamayı buradan indirebilirsiniz.</a></li>
<li><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second.html" target="_blank">Uygulamanın demosunu buradan görebilirsiniz.</a></li>
</ul>
<h3>Örnekler</h3>
<ul>
<li>Penceremize <strong>menü veya buton çubuğu</strong> eklemek istersek aşağıdaki kodu kullanabiliriz.</li>
</ul>
<blockquote><p>tbar: [{<br />
text:'Yeni',<br />
handler: function(){<br />
Ext.Msg.alert('Bilgi', '"' + this.text + '"' + ' butonuna bastınız.');<br />
}<br />
},{<br />
text: 'Sil',<br />
disabled:true<br />
}],</p></blockquote>
<p style="padding-left: 30px;"><img class="alignnone size-full wp-image-165" title="5" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/5.png" alt="5" width="519" height="319" /><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars.rar"></a></p>
<p style="padding-left: 30px;"><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars.rar">İndir</a> |   <a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars.html" target="_blank">Gör</a></p>
<p style="padding-left: 30px;">
<ul>
<li>Penceremize <strong>buton</strong> eklemek istersek aşağıdaki kodu kullanabiliriz.</li>
</ul>
<blockquote><p>buttons: [{<br />
text:'Kaydet',<br />
disabled:true<br />
},{<br />
text: 'Kapat',<br />
handler: function(){<br />
win.hide();<br />
}<br />
}],</p></blockquote>
<p><img class="alignnone size-full wp-image-168" title="6" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/6.png" alt="6" width="517" height="319" /><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-buttons.rar"></a></p>
<p><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-buttons.rar">İndir</a> |   <a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-buttons.html" target="_blank">Gör</a></p>
<ul>
<li>Penceremize <strong>sekme</strong> eklemek istersek aşağıdaki kodu kullanabiliriz.</li>
</ul>
<blockquote><p>items: new Ext.TabPanel({<br />
renderTo: Ext.getBody(),<br />
activeTab:0,<br />
border:false,<br />
items: [{<br />
title: 'Birinci Sekme',<br />
html: 'Birinci sekmenin içeriği burada görüntülenir.'<br />
},{<br />
title: 'İkinci Sekme',<br />
html: 'İkinci sekmenin içeriği burada görüntülenecek. Bu bölüme istediğiniz bilgiyi ekleyebilirsiniz.'<br />
}]<br />
}),</p></blockquote>
<p><img class="alignnone size-full wp-image-169" title="7" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/7.png" alt="7" width="523" height="319" /><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-tabs.rar"></a></p>
<p><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-tabs.rar">İndir</a> |   <a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-tabs.html" target="_blank">Gör</a></p>
<ul>
<li>Bu eklemeleri birlikte de yapabiliriz.</li>
</ul>
<p><img class="alignnone size-full wp-image-170" title="8" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/8.png" alt="8" width="521" height="323" /><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-tabs.rar"></a></p>
<p><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-tabs.rar">İndir</a> |   <a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-tabs.html" target="_blank">Gör</a></p>
<p style="padding-left: 30px;"><img class="alignnone size-full wp-image-171" title="9" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/9.PNG" alt="9" width="519" height="324" /><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-buttons.rar"></a></p>
<p style="padding-left: 30px;"><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-buttons.rar">İndir</a> |   <a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-buttons.html" target="_blank">Gör</a></p>
<p style="padding-left: 30px;">
<p style="padding-left: 30px;"><img class="alignnone size-full wp-image-172" title="10" src="http://www.simsekmert.com/wp/wp-content/uploads/2011/01/10.png" alt="10" width="524" height="324" /><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-tabs-buttons.rar"></a></p>
<p style="padding-left: 30px;"><a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-tabs-buttons.rar">İndir</a> |   <a href="http://www.simsekmert.com/wp/files/extjs/myApp/application/second-bars-tabs-buttons.html" target="_blank">Gör</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2011/01/ext-js-javascript-framework/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>FPDF Türkçe Fontlar</title>
		<link>http://www.simsekmert.com/wp/2010/11/fpdf-turkce-fontlar/</link>
		<comments>http://www.simsekmert.com/wp/2010/11/fpdf-turkce-fontlar/#comments</comments>
		<pubDate>Sun, 28 Nov 2010 22:07:41 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Programlama]]></category>
		<category><![CDATA[font]]></category>
		<category><![CDATA[fpdf]]></category>
		<category><![CDATA[pdf]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[türkçe]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=136</guid>
		<description><![CDATA[FPDF, php ile  pdf e dönüştürme aracı olarak kullanılan bir sınıftır. Fakat bu sınıf kullanılırken karşılaşılan en büyük sorunlardan birisi Türkçe karakter sorunudur.
Aşağıdaki linkte FPDF için kendi yaptığım Türkçe fontları bulabilirsiniz. arial_tr ve arial_tr_bold&#8230; Kolay gelsin
Fontları indirmek için tıklayın&#8230;
]]></description>
			<content:encoded><![CDATA[<p>FPDF, php ile  pdf e dönüştürme aracı olarak kullanılan bir sınıftır. Fakat bu sınıf kullanılırken karşılaşılan en büyük sorunlardan birisi Türkçe karakter sorunudur.</p>
<p><span id="more-136"></span>Aşağıdaki linkte FPDF için kendi yaptığım Türkçe fontları bulabilirsiniz. arial_tr ve arial_tr_bold&#8230; Kolay gelsin</p>
<p><a class="alignleft" title="Türkçe Fontlar" href="http://www.simsekmert.com/wp/files/turkce_fontlar.rar" target="_self">Fontları indirmek için tıklayın&#8230;</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2010/11/fpdf-turkce-fontlar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How To Optimize Your Site With GZIP Compression</title>
		<link>http://www.simsekmert.com/wp/2010/07/how-to-optimize-your-site-with-gzip-compression/</link>
		<comments>http://www.simsekmert.com/wp/2010/07/how-to-optimize-your-site-with-gzip-compression/#comments</comments>
		<pubDate>Sat, 24 Jul 2010 14:32:54 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[Web Programlama]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=134</guid>
		<description><![CDATA[Compression is a simple, effective way to save bandwidth and speed up  your site. I hesitated when recommending gzip compression when speeding up your javascript because of problems in older browsers.
But it’s the 21st century. Most of my traffic comes from modern browsers, and quite frankly, most of my users are fairly tech-savvy. I [...]]]></description>
			<content:encoded><![CDATA[<p>Compression is a simple, effective way to save bandwidth and speed up  your site. I hesitated when recommending gzip compression when <a href="http://betterexplained.com/articles/speed-up-your-javascript-load-time/">speeding up your javascript</a> because of <a href="http://support.microsoft.com/kb/837251">problems</a> <a href="http://support.microsoft.com/kb/823386">in</a> <a href="http://schroepl.net/projekte/mod_gzip/browser.htm">older browsers</a>.</p>
<p>But it’s the 21st century. Most of my traffic comes from modern browsers, and quite frankly, most of <a href="http://instacalc.com/">my users</a> are fairly tech-savvy. I don’t want to slow everyone else down because  somebody is chugging along on IE 4.0 on Windows 95. Google and Yahoo use  gzip compression. A modern browser is needed to enjoy modern web  content and modern web speed — so gzip encoding it is. Here’s how to set  it up.</p>
<p><span id="more-134"></span></p>
<h2>Wait, wait, wait: Why are we doing this?</h2>
<p>Before we start I should explain what content encoding is. When you request a file like <code>http://www.yahoo.com/index.html</code>, your browser talks to a web server. The conversation goes a little like this:</p>
<p><img title="HTTP_request.png" src="http://betterexplained.com/wp-content/uploads/compression/HTTP_request.png" border="0" alt="HTTP_request.png" width="437" height="221" /></p>
<p>1. Browser: Hey, <strong><span>GET</span></strong> me /index.html<br />
2. Server: Ok, let me see if index.html is lying around…<br />
3. Server: Found it! Here’s your response code (200 OK) and I’m sending the file.<br />
4. Browser: 100KB? Ouch… waiting, waiting… ok, it’s loaded.</p>
<p>Of course, the actual headers and protocols are much more formal (monitor them with <a href="http://betterexplained.com/articles/how-to-debug-web-applications-with-firefox/">Live <span>HTTP</span> Headers</a> if you’re so inclined).</p>
<p>But it worked, and you got your file.</p>
<h2>So what’s the problem?</h2>
<p>Well, the system works, but it’s not that efficient. 100KB is a <strong>lot of text</strong>, and frankly, <span>HTML </span>is redundant. Every <code>&lt;html&gt;, &lt;table&gt; and &lt;div&gt;</code> tag has a closing tag that’s almost the same. Words are repeated throughout the document. Any way you slice it, <span>HTML </span>(and its beefy cousin, <span>XML</span>) is not lean.</p>
<p>And what’s the plan when a file’s too big? Zip it!</p>
<p>If we could send a .zip file to the browser (index.html.zip) instead  of plain old index.html, we’d save on bandwidth and download time. The  browser could download the zipped file, extract it, and then show it to  user, who’s in a good mood because the page loaded quickly. The  browser-server conversation might look like this:</p>
<p><img title="HTTP_request_compressed.png" src="http://betterexplained.com/wp-content/uploads/compression/HTTP_request_compressed.png" border="0" alt="HTTP_request_compressed.png" width="436" height="213" /></p>
<p>1. Browser: Hey, can I <strong><span>GET</span></strong> index.html? I’ll take a compressed version if you’ve got it.<br />
2. Server: Let me find the file… yep, it’s here. And you’ll take a compressed version? Awesome.<br />
3. Server: Ok, I’ve found index.html (200 OK), am zipping it and sending it over.<br />
4. Browser: Great! It’s only 10KB. I’ll unzip it and show the user.</p>
<p>The formula is simple: Smaller file = faster download = <strong>happy user</strong>.</p>
<p>Don’t believe me? The <span>HTML </span>portion of the yahoo home page goes from 101kb to 15kb after compression:</p>
<p><img title="yahoo_compression.PNG" src="http://betterexplained.com/wp-content/uploads/compression/yahoo_compression.PNG" border="0" alt="yahoo_compression.PNG" width="391" height="50" /></p>
<h2>The (not so) hairy details</h2>
<p>The tricky part of this exchange is the browser and server knowing  it’s ok to send a zipped file over. The agreement has two parts</p>
<ul>
<li>The <strong>browser sends a header</strong> telling the server it accepts compressed content (gzip and deflate are two compression schemes): <code>Accept-Encoding: gzip, deflate</code></li>
</ul>
<ul>
<li>The <strong>server sends a response</strong> if the content is actually compressed: <code>Content-Encoding: gzip</code></li>
</ul>
<p>If the server doesn’t send the content-encoding response header, it  means the file is not compressed (the default on many servers). The  “Accept-encoding” header is just a request by the browser, not a demand.  If the server doesn’t want to send back compressed content, the browser  has to make do with the heavy regular version.</p>
<h2>Setting up the server</h2>
<p>The “good news” is that we can’t control the browser. It either sends the <code>Accept-encoding: gzip, deflate</code> header or it doesn’t.</p>
<p>Our job is to configure the server so it returns zipped content if  the browser can handle it, saving bandwidth for everyone (and giving us a  happy user).</p>
<p>For <span>IIS, </span><a href="http://technet.microsoft.com/en-us/library/cc771003%28WS.10%29.aspx">enable compression</a> in the settings.</p>
<p>In Apache, <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html">enabling output compression</a> is fairly straightforward. Add the following to your .htaccess file:</p>
<pre><code>
# compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

# Or, compress certain file types by extension:
&lt;Files *.html&gt;
SetOutputFilter DEFLATE
&lt;/Files&gt;
</code></pre>
<p>Apache actually has two compression options:</p>
<ul>
<li><strong>mod_deflate</strong> is easier to set up and is standard.</li>
<li><strong>mod_gzip</strong> seems more powerful: you can pre-compress content.</li>
</ul>
<p>Deflate is quick and works, so I use it; use mod_gzip if that floats  your boat. In either case, Apache checks if the browser sent the  “Accept-encoding” header and returns the compressed or regular version  of the file. However, some older browsers may have trouble (more below)  and there are special directives you can add to correct this.</p>
<p>If you can’t change your .htaccess file, you can <a href="http://perishablepress.com/press/2007/03/26/fast-effective-php-compression/">use <span>PHP</span></a> to return compressed content. Give your <span>HTML </span>file a .php extension and add this code to the top:</p>
<pre><code>
In PHP:
&lt;?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?&gt;
</code></pre>
<p>We check the “Accept-encoding” header and return a gzipped version of  the file (otherwise the regular version). This is almost like building  your own webserver (what fun!). But really, try to use Apache to  compress your output if you can help it. You don’t want to monkey with  your files.</p>
<h2>Verify Your Compression</h2>
<p>Once you’ve configured your server, check to make sure you’re actually serving up compressed content.</p>
<ul>
<li><strong>Online:</strong> Use the <a href="http://www.gidnetwork.com/tools/gzip-test.php">online gzip test</a> to check whether your page is compressed.</li>
<li><strong>In your browser:</strong> Use <a href="https://addons.mozilla.org/en-US/firefox/addon/60">Web Developer Toolbar</a> &gt; Information &gt; View Document Size (like I did for Yahoo, above) to see whether the page is compressed.</li>
<li><strong>View the headers:</strong> Use <a href="https://addons.mozilla.org/en-US/firefox/addon/3829">Live <span>HTTP</span> Headers</a> to examine the response. Look for a line that says “Content-encoding: gzip”.</li>
</ul>
<p>Be prepared to marvel at the results. The <a href="http://instacalc.com/">instacalc homepage</a> shrunk from 36k to 10k, a 75% reduction in size.</p>
<h2>Try Some Examples</h2>
<p>I’ve set up some pages and a <a href="http://betterexplained.com/examples/compressed/compression-example.zip">downloadable example</a>:</p>
<ul>
<li><a href="http://betterexplained.com/examples/compressed/index.html">index.html</a> – No explicit compression (on this server, I am using compression by default <img src="http://betterexplained.com/wp-includes/images/smilies/icon_smile.gif" alt=":)" /> ).</li>
<li><a href="http://betterexplained.com/examples/compressed/index.htm">index.htm</a> – Explicitly compressed with Apache .htaccess using *.htm as a rule</li>
<li><a href="http://betterexplained.com/examples/compressed/index.php">index.php</a> – Explicitly compressed using the <span>PHP </span>header</li>
</ul>
<p>Feel free to download the files, put them on your server and tweak the settings.</p>
<h2>Caveats</h2>
<p>As exciting as it may appear, <span>HTTP</span> Compression isn’t all fun and games. Here’s what to watch out for:</p>
<ul>
<li><strong>Older browsers</strong>: Yes, some browsers still may have  trouble with compressed content (they say they can accept it, but really  they can’t). If your site absolutely must work with Netscape 1.0 on  Windows 95, you may not want to use <span>HTTP</span> Compression. Apache mod_deflate <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html#recommended">has some rules</a> to avoid compression for older browsers.</li>
<li><strong>Already-compressed content</strong>: Most images, music and  videos are already compressed. Don’t waste time compressing them again.  In fact, you probably only need to compress the “big 3″ (HTML, <span>CSS </span>and Javascript).</li>
<li><strong><span>CPU</span>-load</strong>: Compressing content on-the-fly uses <span>CPU </span>time  and saves bandwidth. Usually this is a great tradeoff given the speed  of compression. There are ways to pre-compress static content and send  over the compressed versions. This requires more configuration; even if  it’s not possible, compressing output may still be a net win. Using <span>CPU </span>cycles for a faster user experience is well worth it, given the short attention spans on the web.</li>
</ul>
<p>Enabling compression is one of the fastest ways to improve your  site’s performance. Go forth, set it up, and let your users enjoy the  benefits.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2010/07/how-to-optimize-your-site-with-gzip-compression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fast, Effective PHP Compression</title>
		<link>http://www.simsekmert.com/wp/2010/07/fast-effective-php-compression/</link>
		<comments>http://www.simsekmert.com/wp/2010/07/fast-effective-php-compression/#comments</comments>
		<pubDate>Sat, 24 Jul 2010 14:15:35 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Programlama]]></category>
		<category><![CDATA[compression]]></category>
		<category><![CDATA[gzip]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=132</guid>
		<description><![CDATA[PHP compression is an excellent method of conserving bandwidth and  reducing client download times. We have already discussed an excellent  method for CSS compression, and in this article we share a super-easy technique for compressing all PHP content without editing a single file.
Using two PHP files and two corresponding lines of .htaccess, it [...]]]></description>
			<content:encoded><![CDATA[<p>PHP compression is an excellent method of conserving bandwidth and  reducing client download times. We have already discussed an excellent  method for <a href="http://perishablepress.com/press/2006/10/23/compressed-css-compression/">CSS compression</a>, and in this article we share a super-easy technique for compressing all PHP content without editing a single file.</p>
<p>Using two PHP files and two corresponding lines of .<code>htaccess</code>, it is possible to compress your PHP files via <a title="The gzip Home Page" href="http://www.gzip.org/">gzip-encoding</a>.  Browsers and other user-agents capable of interpreting gz-encoded data  will employ the compressed content, while other user-agents will utilize  the content uncompressed.</p>
<p><span id="more-132"></span></p>
<p><span id="more-341"> </span></p>
<p>Before we begin, it is important to determine if your  server employs output buffering. If so, it may not be necessary to  compress content via this method. Also, this PHP compression technique  requires PHP version 4.0.5 or better.</p>
<p>Now, create two PHP files, &#8220;gzip_start.php&#8221; and &#8220;gzip_stop&#8221;. Open gzip_start.php and add this:</p>
<pre style="overflow: hidden; width: 525px; display: block;"><code>&lt;?php
   ob_start("ob_gzhandler");
?&gt;</code></pre>
<p>Then, open gzip_stop.php and add this:</p>
<pre style="overflow: hidden; width: 525px; display: block;"><code>&lt;?php
   ob_flush();
?&gt;</code></pre>
<p>Save and upload both files to a convenient location on your  server. The first file instructs the server to begin output buffering  via gz-encoding. The second file instructs the server to transmit the  buffered content to the user-agent, assuming it sends a header  indicating its ability to process gzipped data.</p>
<p>Finally, we need a way to include first file at the  beginning of each PHP document and the second file at the end of each  PHP document. Rather than manually adding <code>include()</code> or <code>require()</code> functions to every PHP document, we will summon the mysterious powers of .<code>htaccess</code> to do it all automatically. Simply add the following lines to your .<code>htaccess</code> file:</p>
<pre style="overflow: hidden; width: 525px; display: block;"><code># dual file includes for PHP compression
php_value  auto_prepend_file  /specify/full/path/to/gzip_start.php
php_value  auto_append_file   /specify/full/path/to/gzip_stop.php</code></pre>
<p>Edit the path in each line, save and upload the .<code>htaccess</code> file to your server. These two lines will ensure proper inclusion of  both files to every PHP document subject to their influence (i.e., the  containing directory and all subdirectories). The <code>auto_prepend_file</code> function literally prepends data, while the <code>auto_append_file</code> function, well, you get the idea..</p>
<h3>Alternate Method</h3>
<p>For an even easier PHP-compression method, simply place the following code before the (X)HTML content in any PHP script:</p>
<pre style="overflow: hidden; z-index: 99; position: relative; width: 525px; display: block;"><code>&lt;?php if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start(); ?&gt;</code></pre>
<p>In this case, the <code>ob_flush()</code> command is  unnecessary as PHP inherently flushes the buffer. The script delivers  gzipped content to capable browsers and uncompressed content to  incapable browsers. It’s a win-win!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2010/07/fast-effective-php-compression/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SQL Server, PHP and Truncating Text</title>
		<link>http://www.simsekmert.com/wp/2010/06/sql-server-php-and-truncating-text/</link>
		<comments>http://www.simsekmert.com/wp/2010/06/sql-server-php-and-truncating-text/#comments</comments>
		<pubDate>Sun, 20 Jun 2010 19:45:42 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[MSSQL]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[truncate]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=130</guid>
		<description><![CDATA[PHP and SQL Server are a powerful combination, however sometimes data stored in a text type column is truncated for no apparent reason after 4096 characters. Here&#8217;s how to fix the problem.

PHP can work with a large number of database systems, most common of  which is MySQL. However, SQL Server is a very poweful [...]]]></description>
			<content:encoded><![CDATA[<p>PHP and SQL Server are a powerful combination, however sometimes data stored in a text type column is truncated for no apparent reason after 4096 characters. Here&#8217;s how to fix the problem.</p>
<p><span id="more-130"></span></p>
<p>PHP can work with a large number of database systems, most common of  which is MySQL. However, SQL Server is a very poweful alternative to  MySQL, and well worth considering for larger projects.</p>
<p>However, settings for the mssql extension in PHP can easily be  overlooked, resulting in strange behaviour. One of the most unusual  problems I encountered on a recent project was that every time text was  pulled from a column of type &#8220;text&#8221;, it was truncated at around 4000  characters.</p>
<p>If you are experiencing a similar problem, there are a few ways to  work around it.</p>
<p>You need to increase the maximum size of a text column to be returned  from SQL Server by PHP. You can do this with a simple SQL query:</p>
<p><code>SET TEXTSIZE 2147483647</code></p>
<p>Which you can run with the following PHP (best run just after you  make a connection).</p>
<p><code>mssql_query("SET TEXTSIZE 2147483647");</code></p>
<p>A better way to work around the issue is to change the &#8220;textlimit&#8221;  and &#8220;textsize&#8221; settings within php.ini, like so:</p>
<p><code>mssql.textlimit = 2147483647 mssql.textsize = 2147483647</code></p>
<p>In the above examples, I have used &#8220;2147483647&#8243; (number of bytes) for  the value. You don&#8217;t need to set it this high necessarily, however  there is no real harm in doing so.</p>
<p>And why does this not happen with ASP? When you use Microsoft&#8217;s SQL  Server ODBC driver and OLE DB Provider, textsize is automatically set to  2147483647 when a connection is made.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2010/06/sql-server-php-and-truncating-text/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is the maximum length of a URL?</title>
		<link>http://www.simsekmert.com/wp/2010/03/what-is-the-maximum-length-of-a-url/</link>
		<comments>http://www.simsekmert.com/wp/2010/03/what-is-the-maximum-length-of-a-url/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 07:29:47 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[Web Programlama]]></category>
		<category><![CDATA[length]]></category>
		<category><![CDATA[url]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=106</guid>
		<description><![CDATA[Although the specification of the  HTTP  protocol does not specify any maximum length, practical limits are imposed by web browser and server software.
Microsoft Internet Explorer (Browser)
Microsoft states that  the maximum length of a URL in Internet Explorer is 2,083 characters,  with no  more than 2,048 characters in the path portion [...]]]></description>
			<content:encoded><![CDATA[<p><span id="KonaBody">Although the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html">specification</a> of the  <a href="http://www.boutell.com/newfaq/definitions/http.html">HTTP  protocol</a> does not specify any maximum length, practical limits are imposed by web browser and server software.</span></p>
<h4>Microsoft Internet Explorer (Browser)</h4>
<p><a href="http://support.microsoft.com/kb/q208427/">Microsoft states</a> that  the maximum length of a URL in Internet Explorer is 2,083 characters,  with no  more than 2,048 characters in the path portion of the  <a href="http://www.boutell.com/newfaq/definitions/url.html">URL</a>. In  my tests, attempts to use URLs longer than this produced a clear error message in Internet  Explorer.</p>
<h4>Firefox (Browser)</h4>
<p>After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. I stopped testing   after 100,000 characters.</p>
<p><span id="more-106"></span></p>
<h4>Safari (Browser)</h4>
<p>At least 80,000 characters will work. I stopped testing after  80,000 characters.</p>
<h4>Opera (Browser)</h4>
<p>At least 190,000 characters will work. I stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully  editable, copyable and pasteable URL in the location bar even at 190,000  characters.</p>
<h4>Apache (Server)</h4>
<p>My early attempts to measure the maximum URL length in web browsers  bumped into a server URL length limit of approximately 4,000 characters, after which  Apache produces a &#8220;413 Entity Too Large&#8221; error. I used the current up to date Apache build found in Red Hat Enterprise Linux 4. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.</p>
<h4>Microsoft Internet Information Server</h4>
<p>The default limit is 16,384 characters (yes, Microsoft&#8217;s web server accepts longer URLs than Microsoft&#8217;s web browser). This is configurable.</p>
<h4>Perl HTTP::Daemon (Server)</h4>
<p>Up to 8,000 bytes will work. Those constructing web application servers  with  Perl&#8217;s HTTP::Daemon module will encounter a 16,384 byte limit on the  combined  size of all HTTP request headers. This does <em>not</em> include  POST-method  form data, file uploads, etc., but it does include the URL. In practice  this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of <tt>16x1024</tt> in <tt>Daemon.pm</tt> and replace  them with a larger value. Of course, this does increase your exposure to  denial of service attacks.</p>
<h4>Recommendations</h4>
<p>Extremely long URLs are usually a mistake. URLs over 2,000 characters will not work in the most popular web browser. Don&#8217;t use them if you intend your site to work for the majority of Internet users.When you wish to submit a form  containing many fields, which would otherwise produce a very long URL, the standard solution is to use the POST method rather than the GET  method:</p>
<pre>&lt;form action="myscript.php" method="POST"&gt;
...
&lt;/form&gt;</pre>
<p>The form fields are then transmitted as part of the HTTP transaction body, not as part of the URL, and are not subject to the URL length limit. Short-lived information should not be stored in URLs.As a rule of thumb, if a piece of information isn&#8217;t needed to regenerate  the  same page as a result of returning to a favorite or bookmark, then it  doesn&#8217;t belong in the URL.</p>
<h4>The Bookmark Problem</h4>
<p>In very rare cases, it may be useful to keep a large amount of &#8220;state&#8221;  information in a URL. For instance, users of a map-navigating website might wish to add the currently displayed map to their &#8220;bookmarks&#8221; or &#8220;favorites&#8221; list and return later. If you must do this and your  URLs are approaching 2,000 characters in length, keep your representation of the information as compact as you can, squeezing out as much &#8220;air&#8221; as possible. If your field names take up too much  space, use a fixed field order instead. Squeeze out any field that doesn&#8217;t really need to be bookmarked. And avoid large decimal numbers &#8211; use only as much accuracy as you must, and consider a base-64 representation using letters and digits (I didn&#8217;t say this was easy).In extreme cases, consider using the <a href="http://www.gzip.org/">gzip</a> algorithm to  compress your pretty but excessively long URL. Then reencode that binary data in base64 using only characters that are legal in URLs. This can yield a 3-4x space gain, at the cost of some CPU time when you unzip the URL again on the next visit. Again, I never said  it was easy!</p>
<p>An alternative is to store the state information in a file or a database. Then you can store only the identifier needed to look up that information again in the URL. The disadvantage here is that you will have many state files or database records. Some of which might be linked to on websites run by others. One solution to this problem is to delete the state files or database records for the URLs that have not been revisited after a certain amount of time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2010/03/what-is-the-maximum-length-of-a-url/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating Random Numbers in JavaScript</title>
		<link>http://www.simsekmert.com/wp/2009/08/generating-random-numbers-in-javascript/</link>
		<comments>http://www.simsekmert.com/wp/2009/08/generating-random-numbers-in-javascript/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 21:54:06 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[floor]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[random]]></category>

		<guid isPermaLink="false">http://www.simsekmert.com/wp/?p=103</guid>
		<description><![CDATA[To generate random numbers with JavaScript we employ the random() method of the Math object. It returns a floating-point number between 0.0 and 1.0.
JavaScript Math object has several methods and we shall encounter three on this page &#8211; the first one being random().
var rand_no = Math.random();
alert(rand_no);

In the code above, the random() method returns the number [...]]]></description>
			<content:encoded><![CDATA[<p>To generate random numbers with JavaScript we employ the <span><strong>random()</strong></span> method of the <span><strong>Math</strong></span> object. It returns a floating-point number between 0.0 and 1.0.<br />
JavaScript <strong>Math</strong> object has several methods and we shall encounter three on this page &#8211; the first one being <span>random()</span>.</p>
<pre>var rand_no = Math.random();
alert(rand_no);</pre>
<p><span id="more-103"></span></p>
<p>In the code above, the <span>random()</span> method returns the number which we store in the variable <span>rand_no</span> and display through <span>alert()</span>. <a onclick="rgen()" href="javascript:void(0)">Click to display a random number</a>.<br />
You&#8217;ll notice that each time you click the link a new random number is generated and displayed.</p>
<p>Now that we have our randomly generated number with JavaScript, let us see how we can use it in some of our applications.</p>
<h2>How to use JavaScript random number</h2>
<p>Suppose you want a random number between 1 and 100. How do you get it from the long decimal number thrown up by the <span>random()</span> method?</p>
<p>The first step is to multiply the long decimal random number generated by the random() method with 100.</p>
<pre>var rand_no = Math.random();
rand_no = rand_no * 100;
alert(rand_no);</pre>
<p>Click to get see a set of 10 <a onclick="rgen2()" href="javascript:void(0)">random numbers</a>.</p>
<p>The code above will give us a random number between 0 and 10. All numbers will be a little more than 0 and a little les than 100 &#8211; and they still have the long tail of numbers after the decimal. The next step involves another method of the JavaScript <span>Math()</span> object called <span><strong>ceil()</strong></span>.</p>
<h2>JavaScript ceil() method</h2>
<p>The JavaScript ceil() rounds a decimal number to the <strong><em>next higher integer</em></strong>. Thus,</p>
<pre>Math.ceil(2.456)		//gives 3
Math.ceil(46.9)		//gives 47
Math.ceil(0.0006)		// gives 1</pre>
<p>To remove numbers after the decimal and provide us with an integer between 1 and 100, we will pass the random number generated by <span>random()</span> to <span>ceil()</span>.</p>
<pre>var rand_no = Math.random();
rand_no = rand_no * 100;
rand_no = Math.ceil(rand_no);
alert(rand_no);</pre>
<p><a onclick="rgen3()" href="javascript:void(0)">Click to generate a random number between 1 and 100</a>.<br />
The above set of statements can also be shortened to:</p>
<pre>var rand_no = Math.ceil(100*Math.random())
alert(rand_no);</pre>
<p>JavaScript generates random numbers based on a formula. In a sense this is not random because if you know the formula, you know which number will come up next. However, this works fine for the web applications you will develop.<br />
<a onclick="rgen4()" href="javascript:void(0)">Get a list of 20 randomly gerenated numbers between 1 and 100</a>.</p>
<p><strong>What if you want random numbers between 0 and 10?</strong><br />
The question is important. Because if we use the above code, it will simply not work. Since <span>ceil()</span> always returns the next higher integer, all random number that are between 0 and 1 will be converted to 1.<br />
We will learn about another JavaScript method to solve this problem.</p>
<h2>Math.floor() method</h2>
<p>The <span>floor()</span> <strong>rounds a number down to the lower integer</strong>. Thus:</p>
<pre>Math.floor(2.456)		//gives 2
Math.floor(46.9)		//gives 46
Math.floor(0.0006)		// gives 0
Math.floor(1.0006)		// gives 1
Math.floor(0.932)		// gives 0</pre>
<p>But this throws up another problem. Number between 0.9 and 1.0 will all be rounded down (after multiplying with 10) to 9!<br />
The solution lies in multiplying the random number generated by <span>random()</span> with 11 &#8211; one number more than the range.</p>
<pre>var rand_no = Math.floor(11*Math.random())
alert(rand_no);</pre>
<p><a onclick="rgen5()" href="javascript:void()">List of 20 random number between 0 and 10</a>.</p>
<h2>Random number from a given range</h2>
<p>To generate random numbers from a given range, follow the steps below:</p>
<ul>
<li>Get number between 0.0 and 1.0 from <span>random()</span> method.</li>
<li>Multiply it with the difference of upper value and <em>one less than</em> the lower value of the range.</li>
<li>Use <span>floor()</span> to convert it into an integer</li>
<li>Add the lower value of the range</li>
</ul>
<pre>var rand_no = Math.floor((10-4)*Math.random()) + 5;
alert(rand_no);</pre>
<p>The code above generates a random number between 5 and 10. Just to prove that this works beautifully <a onclick="rgen6()" href="javascript:void()">click to get a list of 20 random number between 5 and 10</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2009/08/generating-random-numbers-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>25 Excellent jQuery Tips</title>
		<link>http://www.simsekmert.com/wp/2009/04/25-excellent-jquery-tips/</link>
		<comments>http://www.simsekmert.com/wp/2009/04/25-excellent-jquery-tips/#comments</comments>
		<pubDate>Fri, 10 Apr 2009 17:15:57 +0000</pubDate>
		<dc:creator>Şimşek Mert</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[web 2.0]]></category>

		<guid isPermaLink="false">http://localhost/wordpress/?p=3</guid>
		<description><![CDATA[jQuery is awesome. I've been using it for about a year now and although I was impressed to begin with I'm liking it more and more the longer I use it and the more I find out about it's inner workings.

I'm no jQuery expert. I don't claim to be, so if there are mistakes in this article then feel free to correct me or make suggestions for improvements.

I'd call myself an "intermediate" jQuery user and I thought some others out there could benefit from all the little tips, tricks and techniques I've learned over the past year. The article also ended up being a lot longer than I thought it was going to be so I'll start with a table of contents so you can skip to the bits you're interested in.]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>jQuery is awesome. I&#8217;ve been using it for about a year now and although I was impressed to begin with I&#8217;m liking it more and more the longer I use it and the more I find out about it&#8217;s inner workings.</p>
<p>I&#8217;m no jQuery expert. I don&#8217;t claim to be, so if there are mistakes in this article then feel free to correct me or make suggestions for improvements.</p>
<p>I&#8217;d call myself an &#8220;intermediate&#8221; jQuery user and I thought some others out there could benefit from all the little tips, tricks and techniques I&#8217;ve learned over the past year. The article also ended up being a lot longer than I thought it was going to be so I&#8217;ll start with a table of contents so you can skip to the bits you&#8217;re interested in.</p>
<p><span id="more-3"></span></p>
<h3>Table of Contents</h3>
<ul>
<li><a href="#tip1"> 1.  Load the framework from Google Code</a></li>
<li><a href="#tip2"> 2.  Use a cheat sheet</a></li>
<li><a href="#tip3"> 3.  Combine all your scripts and minify them</a></li>
<li><a href="#tip4"> 4.  Use Firebug&#8217;s excellent console logging facilities</a></li>
<li><a href="#tip5"> 5.  Keep selection operations  to a minimum by caching</a></li>
<li><a href="#tip6"> 6.  Keep DOM manipulation to a minimum</a></li>
<li><a href="#tip7"> 7.  Wrap everything in a single element when doing any kind of DOM insertion</a></li>
<li><a href="#tip8"> 8.  Use IDs instead of classes wherever possible</a></li>
<li><a href="#tip9"> 9.  Give your selectors a context</a></li>
<li><a href="#tip10">10.  Use chaining properly</a></li>
<li><a href="#tip11">11.  Learn to use animate properly</a></li>
<li><a href="#tip12">12.  Learn about event delegation</a></li>
<li><a href="#tip13">13.  Use classes to store state</a></li>
<li><a href="#tip14">14.  Even better, use jQuery&#8217;s internal data() method to store state</a></li>
<li><a href="#tip15">15.  Write your own selectors</a></li>
<li><a href="#tip16">16.  Streamline your HTML and modify it once the page has loaded</a></li>
<li><a href="#tip17">17.  Lazy load content for speed and SEO benefits</a></li>
<li><a href="#tip18">18.  Use jQuery&#8217;s utility functions</a></li>
<li><a href="#tip19">19.  Use noconflict to rename the jquery object when using other frameworks</a></li>
<li><a href="#tip20">20.  How to tell when images have loaded</a></li>
<li><a href="#tip21">21.  Always use the latest version</a></li>
<li><a href="#tip22">22.  How to check if an element exists</a></li>
<li><a href="#tip23">23.  Add a JS class to your HTML attribute</a></li>
<li><a href="#tip24">24.  Return &#8216;false&#8217; to prevent default behaviour</a></li>
<li><a href="#tip25">25.  Shorthand for the ready event</a></li>
</ul>
<p><a title="tip1" name="tip1"></a></p>
<h3>1. Load the framework from Google Code</h3>
<p>Google have been hosting several JavaScript libraries for a while now on Google Code and there are several advantages to loading it from them instead of from your server. It saves on bandwidth, it&#8217;ll load very quickly from Google&#8217;s CDN and most importantly it&#8217;ll already be cached if the user has visited a site which delivers it from Google Code.</p>
<p>This makes a lot of sense. How many sites out there are serving up identical copies of jQuery that aren&#8217;t getting cached? It&#8217;s easy to do too&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">&lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
// Load jQuery
google.load("jquery", "1.2.6");
google.setOnLoadCallback(function() {
 // Your code goes here.
});
&lt;/script&gt;</pre>
<p>Or, you can just include a direct reference like this&#8230;</p>
<pre class="xml">&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt;</pre>
<p><a href="http://code.google.com/apis/ajaxlibs/documentation/index.html">Full instructions here</a></p>
<p><a title="tip2" name="tip2"></a></p>
<h3>2. Use a cheat sheet</h3>
<p>Not just a jQuery tip, there are some great cheat sheets out there for most languages. It&#8217;s handy having every function on a printable A4 sheet for reference and luckily these guys have produced a couple of nice ones..</p>
<p><a href="http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/">http://www.gscottolson.com/weblog/2008/01/11/jquery-cheat-sheet/</a><br />
<a href="http://colorcharge.com/jquery/">http://colorcharge.com/jquery/</a></p>
<p><a title="tip3" name="tip3"></a></p>
<h3>3. Combine all your scripts and minify them</h3>
<p>OK, a general JavaScript tip here. But any big project that uses lots of jQuery probably uses lots of plugins (this site uses easing, localScroll, lightbox and preload) so it&#8217;s usually applicable.</p>
<p>Browsers can&#8217;t load scripts concurrently (well, most can&#8217;t, yet), which means that if you&#8217;ve got several scripts downloading one at a time then you&#8217;re really slowing down the loading of your page. So, assuming the scrips are being loaded on every page then you should consider combining them into one long script before deploying.</p>
<p>Some of the plugins will already be minified, but you should consider packing your scripts and any that aren&#8217;t already. It only takes a few seconds. I&#8217;m personally a fan of <a href="http://dean.edwards.name/packer/">Packer by Dean Edwards</a></p>
<p><a title="tip4" name="tip4"></a></p>
<h3>4. Use Firebug&#8217;s excellent console logging facilities</h3>
<p>If you haven&#8217;t already installed Firebug then you really should. Aside from many other useful features such as allowing you to inspect http traffic and find problems with your CSS it has excellent logging commands that allow you to easily debug your scripts.</p>
<p><a href="http://getfirebug.com/console.html">Here&#8217;s a full explanation of all of it&#8217;s features</a></p>
<p>My favourite features are &#8220;console.info&#8221;, which you can use to just dump messages and variables to the screen without having to use alert boxes and &#8220;console.time&#8221; which allows you to easily set up a timer to wrap a bunch of code and see how long it takes. They&#8217;re all really easy to use too&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">console.time('create list');
for (i = 0; i &lt; 1000; i++) {
   var myList = $('.myList');
   myList.append('This is list item ' + i);
}
console.timeEnd('create list');</pre>
<p>In this instance I&#8217;ve deliberately written some very inefficient code! In the next few tips I&#8217;ll show you how we can use the timer to show some improvements which can be made.</p>
<p><a title="tip5" name="tip5"></a></p>
<h3>5. Keep selection operations  to a minimum by caching</h3>
<p>jQuery selectors are awesome. They make selecting any element on the page incredibly simple, but internally they have to do a fair amount of work and if you go mad with them you might find things starting to get pretty slow.</p>
<p>If you&#8217;re selecting the same element time and time again (in a loop for example) then you can just select it once and keep it in memory while you manipulate it to your heart&#8217;s content. Take the following example where we add items to an unordered list using a loop.</p>
<pre class="Jscript" style="padding-left: 30px;">for (i = 0; i &lt; 1000; i++) {
   var myList = $('.myList');
   myList.append('This is list item ' + i);
}</pre>
<p>That takes 1066 milliseconds on my PC in Firefox 3 (imagine how long it would IE6!), which is pretty slow in JavaScript terms. Now take a look at the following code where we use the selector just once.</p>
<pre class="Jscript" style="padding-left: 30px;">var myList = $('.myList');
for (i = 0; i &lt; 1000; i++) {
   myList.append('This is list item ' + i);
}</pre>
<p>That only takes 224 milliseconds, more than 4x faster, just by moving one line of code.</p>
<p><a title="tip6" name="tip6"></a></p>
<h3>6. Keep DOM manipulation to a minimum</h3>
<p>We can make the code from the previous tip even faster by cutting down on the number of times we insert into the DOM. DOM insertion operations like .append() .prepend() .after() and .wrap() are relatively costly and performing lots of them can really slow things down.</p>
<p>All we need to do is use string concatenation to build the list and then use a single function to add them to your unordered list like .html() is much quicker. Take the following example&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">var myList = $('#myList');
for (i=0; i&lt;1000; i++){
   myList.append('This is list item ' + i);
}</pre>
<p>On my PC that takes 216 milliseconds , just over a 1/5th of a second, but if we build the list items as a string first and use the HTML method to do the insert, like this&#8230;.</p>
<pre class="Jscript" style="padding-left: 30px;">var myList = $('.myList');
var myListItems = '';
for (i = 0; i &lt; 1000; i++) {
   myListItems += '&lt;li&gt;This is list item ' + i + '&lt;/li&gt;';
}
myList.html(myListItems);</pre>
<p>That takes 185 milliseconds, not much quicker but that&#8217;s another 31 milliseconds off the time.</p>
<p><a title="tip7" name="tip7"></a></p>
<h3>7. Wrap everything in a single element when doing any kind of DOM insertion</h3>
<p>OK, don&#8217;t ask me why this one works (I&#8217;m sure a more experienced coder will explain).</p>
<p>In our last example we inserted 1000 list items into an unordered list using the .html() method. If we had have wrapped them in the UL tag before doing the insert and inserted the completed UL into another tag (a DIV) then we&#8217;re effectively only inserting 1 tag, not 1000, which seems to be much quicker. Like this&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">var myList = $('.myList');
var myListItems = '&lt;ul&gt;';
for (i = 0; i &lt; 1000; i++) {
   myListItems += '&lt;li&gt;This is list item ' + i + '&lt;/li&gt;';
}
myListItems += '&lt;/ul&gt;'; myList.html(myListItems);</pre>
<p>The time is now only 19 milliseconds, a massive improvement, 50x faster than our first example.</p>
<p><a title="tip8" name="tip8"></a></p>
<h3>8. Use IDs instead of classes wherever possible</h3>
<p>jQuery makes selecting DOM elements using classes as easy as selecting elements by ID used to be, so it&#8217;s tempting to use classes much more liberally than before. It&#8217;s still much better to select by ID though because jQuery uses the browser&#8217;s native method (getElementByID) to do this and doesn&#8217;t have to do any of it&#8217;s own DOM traversal, which is much faster. How much faster? Let&#8217;s find out.</p>
<p>I&#8217;ll use the previous example and adapt it so each LI we create has a unique class added to it. Then I&#8217;ll loop through and select each one once.</p>
<pre class="Jscript" style="padding-left: 30px;">// Create our list
var myList = $('.myList');
var myListItems = '&lt;ul&gt;';
for (i = 0; i &lt; 1000; i++) {
   myListItems += '&lt;li class="listItem' + i + '"&gt;This is a list item&lt;/li&gt;';
}
myListItems += '&lt;/ul&gt;'; myList.html(myListItems);  

// Select each item once
for (i = 0; i &lt; 1000; i++)
{
   var selectedItem = $('.listItem' + i);
}</pre>
<p>Just as I thought my browser had hung, it finished, in 5066 milliseconds (over 5 seconds). So i modified the code to give each item an ID instead of a class and then selected them using the ID.</p>
<pre class="Jscript" style="padding-left: 30px;">// Create our list
var myList = $('.myList');
var myListItems = '&lt;ul&gt;';
for (i = 0; i &lt; 1000; i++) {
   myListItems += '&lt;li id="listItem' + i + '"&gt;This is a list item&lt;/li&gt;';
}
myListItems += '&lt;/ul&gt;';
myList.html(myListItems);  

// Select each item once
for (i = 0; i &lt; 1000; i++) {
   var selectedItem = $('#listItem' + i);
}</pre>
<p>This time it only took 61 milliseconds. Nearly 100x faster.</p>
<p><a title="tip9" name="tip9"></a></p>
<h3>9. Give your selectors a context</h3>
<p>By default, when you use a selector such as $(&#8217;.myDiv&#8217;) the whole of the DOM will be traversed, which depending on the page could be expensive.</p>
<p>The jQuery function takes a second parameter when performing a selection.</p>
<p><strong>jQuery( expression, context )</strong></p>
<p>By providing a context to the selector, you give it an element to start searching within so that it doesn&#8217;t have to traverse the whole of the DOM.</p>
<p>To demonstrate this, let&#8217;s take the first block of code from the tip above. It creates an unordered list with 1000 items, each with an individual class. It then loops through and selects each item once. You&#8217;ll remember that when selecting by class it took just over 5 seconds to select all 1000 of them using this selector.</p>
<pre class="Jscript" style="padding-left: 30px;">var selectedItem = $('#listItem' + i);</pre>
<p>I then added a context so that it was only running the selector inside the unordered list, like this&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">var selectedItem = $('#listItem' + i, $('.myList'));</pre>
<p>It still took 3818 milliseconds because it&#8217;s still horribly inefficient, but that&#8217;s more than a 25% speed increase by making a small modification to a selector.</p>
<p><a title="tip10" name="tip10"></a></p>
<h3>10. Use chaining properly</h3>
<p>One of the coolest things about jQuery is it&#8217;s ability to chain method calls together. So, for example, if you want to switch the class on an element.</p>
<pre class="Jscript" style="padding-left: 30px;">$('myDiv').removeClass('off').addClass('on');</pre>
<p>If you&#8217;re anything like me then you probably learned that in your first 5 minutes of reading about jQuery but it goes further than that. Firstly, it still works across line breaks (because jQuery = JavaScript), which means you can write neat code like this&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">$('#mypanel').find('TABLE .firstCol').removeClass('.firstCol').css('background' : 'red').append('&lt;span&gt;This cell is now red&lt;/span&gt;');</pre>
<p>Making a habit of using chaining automatically helps you to cut down on your selector use too.</p>
<p>But it goes further than that. Let&#8217;s say that you want to perform several functions on an element but one of the first functions changes the element in some way, like this&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">$('#myTable').find('.firstColumn').css('background','red');</pre>
<p>We&#8217;ve selected a table, drilled down to find cells with a class of &#8220;firstColumn&#8221; and coloured them in red.</p>
<p>Let&#8217;s say we now want to colour all the cells with a class of &#8220;lastColumn&#8221; blue. Because we&#8217;ve used the find() funciton we&#8217;ve filtered out all the cells that don&#8217;t have a class of &#8220;firstColumn&#8221; so we need to use the selector again to get the table element and we can&#8217;t continue chaining, right? Luckily jQuery has an end() function which actually reverts back to the previous unaltered selection so you can carry on chaining, like this&#8230;</p>
<pre class="Jscript" style="padding-left: 30px;">$('#myTable').find('.firstColumn').css('background','red').end().find('.lastColumn').css('background','blue');</pre>
<p>It&#8217;s also easier than you might think to write your own jQuery function which can chain. All you have to do is write a function which modifies an element and returns it.</p>
<pre class="Jscript" style="padding-left: 30px;">$.fn.makeRed = function() {
   return $(this).css('background', 'red');
}
$('#myTable').find('.firstColumn').makeRed().append('hello');</pre>
<p>How easy was that?</p>
<p><a title="tip11" name="tip11"></a></p>
<h3>11. Learn to use animate properly</h3>
<p>When I first started using jQuery I loved the fact that it was easy to use the pre-defined animations like slideDown() and fadeIn() to get some really cool effects incredibly easy. It&#8217;s easy to take things further though because jQuery&#8217;s animate() method is very easy to use and very powerful. In fact, is you look at the jQuery source code you&#8217;ll see that internally those methods are just shortcuts which use the animate() function.</p>
<pre class="Jscript" style="padding-left: 30px;">slideDown: function(speed,callback){
   return this.animate({height: "show"}, speed, callback); },
   fadeIn: function(speed, callback){
      return this.animate({opacity: "show"}, speed, callback);
}</pre>
<p>The animate() method simply takes any CSS style and smoothly transitions it from one value to another. So, you can change the width, height, opacity, background-color, top, left, margin, color, font-size, anything you want.</p>
<p>This is how easy it is to animate all your menu items grow to 100 pixels high when you roll over them.</p>
<pre class="Jscript">$('#myList li').mouseover(function() {     $(this).animate({"height": 100}, "slow"); });</pre>
<p>Unlike other jQuery functions, animations are automatically queued, so if you want to run a second animation once the first is finished then just call the animate method twice, no callback necessary.</p>
<pre class="Jscript">$('#myBox').mouseover(function() {     $(this).animate({ "width": 200 }, "slow");     $(this).animate({"height": 200}, "slow"); });</pre>
<p>If you want the animations to happen concurrently then just put both styles in the params object of a single call, like this&#8230;</p>
<pre class="Jscript">$('#myBox').mouseover(function() {     $(this).animate({ "width": 200, "height": 200 }, "slow"); });</pre>
<p>You can animate any property that&#8217;s numeric. You can also download plugins to help you animate properties that aren&#8217;t, like <a href="http://plugins.jquery.com/project/color">colors and background colors</a></p>
<p><a title="tip12" name="tip12"></a></p>
<h3>12. Learn about event delegation</h3>
<p>jQuery makes it easier than ever to attach events to elements in the DOM unobtrusively, which is great, but adding too many events is inefficient. Event delegation allows you to add less events to achieve the same result in many situations. The best way to illustrate this is with an example&#8230;</p>
<pre class="Jscript">$('#myTable TD').click(function(){     $(this).css('background', 'red'); });</pre>
<p>A simple function which turns cells in a table red when you click on them. Let&#8217;s say that you&#8217;ve got a grid with 10 columns and 50 rows though, that&#8217;s 500 events bound. Wouldn&#8217;t it be neater if we could just attach a single event to the table and when the table is clicked have the event handler work out which cell was clicked before turning it red?</p>
<p>Well that&#8217;s exactly what event delegation is and it&#8217;s easy to implement&#8230;</p>
<pre class="Jscript">$('#myTable').click(function(e) {     var clicked = $(e.target);     clicked.css('background', 'red'); });</pre>
<p>&#8216;e&#8217; contains information about the event, including the target element that actually received the click. All we have to do is inspect it to see which cell was actually clicked. Much neater.</p>
<p>Event delegation has another benefit. Normally, When you bind a handler to a collection of elements it gets attached to those elements and those elements only. If you add new elements to the DOM which would have been matched by the selector then they don&#8217;t have the event handler bound to them (are you following me?) then nothing will happen.</p>
<p>When using event delegation you can add as many matching elements to the DOM as you like after the event is bound and they work too.</p>
<p><a title="tip13" name="tip13"></a></p>
<h3>13. Use classes to store state</h3>
<p>This is the most basic way of storing information about a block of html. jQuery is great at manipulating elements based upon their classes, so if you need to store information about the state of an element then why not add an extra class to store it?</p>
<p>Here&#8217;s an example. We want to create an expanding menu. When you click the button we want the panel to slideDown() if it&#8217;s currently closed, or slideUp() if it&#8217;s currently open. We&#8217;ll start with the HTML</p>
<pre class="xml">&lt;div class="menuItem expanded"&gt;     &lt;div class="button"&gt;         click me     &lt;/div&gt;     &lt;div class="panel"&gt;          &lt;ul&gt;             &lt;li&gt;Menu item 1&lt;/li&gt;             &lt;li&gt;Menu item 2&lt;/li&gt;             &lt;li&gt;Menu item 3&lt;/li&gt;          &lt;/ul&gt;     &lt;/div&gt; &lt;/div&gt;</pre>
<p>Very simple! We&#8217;ve just added an extra class to the wrapper div which serves no other purpose other than to tell us the state of the item. So all we need is a click event handler which performs slideUp() or slideDown() on the corresponding panel when the button is clicked.</p>
<pre class="Jscript">$('.button').click(function() {      var menuItem = $(this).parent();     var panel = menuItem.find('.panel');      if (menuItem.hasClass("expanded")) {         menuItem.removeClass('expanded').addClass('collapsed');         panel.slideUp();     }     else if (menuItem.hasClass("collapsed")) {         menuItem.removeClass('collapsed').addClass('expanded');         panel.slideDown();     } });</pre>
<p>That&#8217;s a very simple example, but you can add extra classes for storing all sorts of information about an element or HTML fragment.</p>
<p>However, in all but simple cases it&#8217;s probably better to use the next tip.</p>
<p><a title="tip14" name="tip14"></a></p>
<h3>14. Even better, use jQuery&#8217;s internal data() method to store state</h3>
<p>It&#8217;s not very well documented for some reason but jQuery has an internal data() method which can be used to store information in key/value pairs against any DOM element. Storing a piece of data is as simple as this&#8230;</p>
<pre class="Jscript">$('#myDiv').data('currentState', 'off');</pre>
<p>We can amend the example from the previous tip. We&#8217;ll use the same HTML (with the &#8220;expanded&#8221; class removed) and use the data() function instead.</p>
<pre class="Jscript">$('.button').click(function() {      var menuItem = $(this).parent();     var panel = menuItem.find('.panel');      if (menuItem.data('collapsed')) {         menuItem.data('collapsed', false);         panel.slideDown();       }     else {         menuItem.data('collapsed', true);         panel.slideUp();     } });</pre>
<p>I&#8217;m sure you&#8217;ll agree this is much neater. For more information about data() and removeData(), see this page&#8230;</p>
<p><a href="http://docs.jquery.com/Internals">jQuery internals</a></p>
<p><a title="tip15" name="tip15"></a></p>
<h3>15. Write your own selectors</h3>
<p>jQuery has loads of built-in selectors for selecting elements by ID, class, tag, attribute and many more. But what do you do when you need to select elements based upon something else and jQuery doesn&#8217;t have a selector?</p>
<p>Well, one answer would be to add classes to the elements from the start and use those to select them, but it turns out that it&#8217;s not hard to extend jQuery to add new selectors.</p>
<p>The best way to demonstrate is with an example.</p>
<pre class="Jscript">$.extend($.expr[':'], {     over100pixels: function(a) {         return $(a).height() &gt; 100;     } });  $('.box:over100pixels').click(function() {     alert('The element you clicked is over 100 pixels high'); });</pre>
<p>The first block of code creates a custom selector which finds any element that is more than 100 pixels tall. The second block just uses it to add a click handler to all those elements.</p>
<p>I won&#8217;t go into any more detail here but you can imagine how powerful this is and if you search google for &#8220;custom jquery selector&#8221; you&#8217;ll find loads of great examples.</p>
<p><a title="tip16" name="tip16"></a></p>
<h3>16. Streamline your HTML and modify it once the page has loaded</h3>
<p>The title might not make a lot of sense but this tip can potentially neaten up your code, reduce the weight and download time of your page and help your SEO. Take the following HTML for example&#8230;</p>
<pre class="Jscript"> &lt;div class="fieldOuter"&gt;     &lt;div class="inner"&gt;         &lt;div class="field"&gt;This is field number 1&lt;/div&gt;     &lt;/div&gt;     &lt;div class="errorBar"&gt;          &lt;div class="icon"&gt;&lt;img src="icon.png" alt="icon" /&gt;&lt;/div&gt;         &lt;div class="message"&gt;&lt;span&gt;This is an error message&lt;/span&gt;&lt;/div&gt;      &lt;/div&gt; &lt;/div&gt; &lt;div class="fieldOuter"&gt;     &lt;div class="inner"&gt;         &lt;div class="field"&gt;This is field number 2&lt;/div&gt;      &lt;/div&gt;     &lt;div class="errorBar"&gt;         &lt;div class="icon"&gt;&lt;img src="icon.png" alt="icon" /&gt;&lt;/div&gt;          &lt;div class="message"&gt;&lt;span&gt;This is an error message&lt;/span&gt;&lt;/div&gt;     &lt;/div&gt; &lt;/div&gt;</pre>
<p>That&#8217;s an example of how a form might be marked up, modified slightly for illustrative purposes. I&#8217;m sure you&#8217;ll agree it&#8217;s pretty ugly and if you had a long form you&#8217;d end up with a fairly long ugly page. It&#8217;s be nicer if you could just put this in your HTML.</p>
<pre class="xml">&lt;div class="field"&gt;This is field 1&lt;/div&gt;  &lt;div class="field"&gt;This is field 2&lt;/div&gt; &lt;div class="field"&gt;This is field 3&lt;/div&gt; &lt;div class="field"&gt;This is field 4&lt;/div&gt; &lt;div class="field"&gt;This is field 5&lt;/div&gt;</pre>
<p>All you have to do is a bit of jQuery manipulation to add all the ugly HTML back in. Like this&#8230;</p>
<pre class="Jscript">$(document).ready(function() {     $('.field').before('&lt;div class="fieldOuter"&gt;&lt;div class="inner"&gt;');     $('.field').after('&lt;/div&gt;&lt;div class="errorBar"&gt;&lt;div class="icon"&gt;         &lt;img src="icon.png" alt="icon" /&gt;&lt;/div&gt;&lt;div class="message"&gt;          &lt;span&gt;This is an error message&lt;/span&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;'); });</pre>
<p>It&#8217;s not always advisable to do this, you&#8217;ll get a bit of a flash as the page loads, but in certain situations where you&#8217;ve got a lot of repeated HTML it can really reduce your page weight and the SEO benefits of reducing all your repeated extraneous markup should be obvious.</p>
<p><a title="tip17" name="tip17"></a></p>
<h3>17. Lazy load content for speed and SEO benefits</h3>
<p>Another way to speed up your page loads and neaten up the HTML that search spiders see is to lazy load whole chunks of it using an AJAX request after the rest of the page has loaded. The user can get browsing right away and spiders only see the content you want them to index.</p>
<p>We&#8217;ve used this technique on our own site. Those purple buttons at the top of the page drop down 3 forms, directions and a google map, which was doubling the size of our pages. So, we just put all that HTML in a static page and use the load() function to load it in once the DOM was ready. Like this&#8230;</p>
<pre class="Jscript">$('#forms').load('content/headerForms.html', function() {     // Code here runs once the content has loaded     // Put all your event handlers etc. here.             });</pre>
<p>I wouldn&#8217;t use this everywhere. You have to consider the trade offs here. You&#8217;re making extra requests to the server and portions of your page might not be available to the user right away, but used correctly it can be a great optimization technique.</p>
<p><a title="tip18" name="tip18"></a></p>
<h3>18. Use jQuery&#8217;s utility functions</h3>
<p>jQuery isn&#8217;t just about flash effects. The creator has exposed some really useful methods which fill a few gaps in JavaScript&#8217;s repertoire.</p>
<p><a href="http://docs.jquery.com/Utilities">http://docs.jquery.com/Utilities</a></p>
<p>In particular, browser support for certain common array functions is patchy (IE7 doesn&#8217;t even have an indexOf() method!). Jquery has methods for iterating, filtering, cloning, merging and removing duplicates from Arrays.</p>
<p>Other common functions that are difficult in Javascript include getting the selected item in a drop down list. In plain old JavaScript you&#8217;d have to get the &lt;select&gt; element using getElementByID, get the child elements as an array and iterate through them checking whether each one was selected or not. jQuery makes it easy&#8230;</p>
<pre class="Jscript">$('#selectList').val();</pre>
<p>It&#8217;s worth spending some time looking through the jQuery documentation on the main site and having a nose around some of the lesser known functions.</p>
<p><a title="tip19" name="tip19"></a></p>
<h3>19. Use noconflict to rename the jquery object when using other frameworks</h3>
<p>Most javascript frameworks make use of the $ symbol as a shorthand and this can cause clashes when trying to use more than one framework on the same page. Luckily there&#8217;s a simple solution. The .noconflict() function gives control of the $ back and allows you to set your own variable name, like this&#8230;</p>
<pre class="Jscript">var $j = jQuery.noConflict(); $j('#myDiv').hide();</pre>
<p><a title="tip20" name="tip20"></a></p>
<h3>20. How to tell when images have loaded</h3>
<p>This is another one of those problems that doesn&#8217;t seem to be as well documented as it should be (not when I went looking anyway) and it&#8217;s a fairly common requirement when building photo galleries, carousels etc,  but it&#8217;s fairly easy.</p>
<p>All you have to do is use the .load() method on an IMG element and put a callback function in it. The following example changes the &#8220;src&#8221; attribute of an image tag to load a new image and attaches a simple load function.</p>
<pre class="Jscript">$('#myImage').attr('src', 'image.jpg').load(function() {     alert('Image Loaded'); });</pre>
<p>You should find that the alert is called as soon as the image is loaded.</p>
<p><a title="tip21" name="tip21"></a></p>
<h3>21. Always use the latest version</h3>
<p>jQuery is constantly improving and John Resig, it&#8217;s creator, always seems to be in search of ways to improve performance.</p>
<p>jQuery is currently on version 1.2.6 but John has already revealed that he&#8217;s working on a new selector engine called <a href="http://ajaxian.com/archives/sizzle-john-resig-has-a-new-selector-engine">Sizzle</a>, which may apparently improve selector speeds in Firefox by up to 4x. So, it pays to keep up to date.</p>
<p><a title="tip22" name="tip22"></a></p>
<h3>22. How to check if an element exists</h3>
<p>You don&#8217;t need to check if an element exists on the page before you manipulate it because jQuery will will simply do nothing if you try to select something and it isn&#8217;t in the DOM. But when you do need to check if anything has been selected, or how many items have been selected you can use the length property.</p>
<pre class="Jscript">if ($('#myDiv).length) {     // your code }</pre>
<p>Simple, but not obvious.</p>
<p><a title="tip23" name="tip23"></a></p>
<h3>23. Add a JS class to your HTML attribute</h3>
<p>I learned this tip from Karl Swedberg whose <a href="http://www.amazon.co.uk/Learning-JQuery-Interaction-Development-Javascript/dp/1847192505/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1229284831&amp;sr=8-1">excellent</a> <a href="http://www.amazon.co.uk/JQuery-Reference-Guide-Karl-Swedberg/dp/1847193811/ref=sr_1_3?ie=UTF8&amp;s=books&amp;qid=1229284831&amp;sr=8-3">books</a> I used to learn jQuery.</p>
<p>He recently left a comment on one of my previous articles about this technique and the basics are as follows&#8230;</p>
<p>Firstly, as soon as jQuery has loaded you use it to add a &#8220;JS&#8221; class to your HTML tag.</p>
<pre class="Jscript"> $('HTML').addClass('JS');</pre>
<p>Because that only happens when javascript is enabled you can use it to add CSS styles which only work if the user has JavaScript switched on, like this&#8230;</p>
<pre class="css">.JS #myDiv{display:none;}</pre>
<p>So, what this means is that we can hide content when JavaScript is switched on and then use jQuery to show it when necessary (e.g. by collapsing some panels and expanding them when the user clicks on them), while those with JavaScript off (and search engine spiders) see all of the content as it&#8217;s not hidden. I&#8217;ll be using this one a lot in the future.</p>
<p>To read his full article <a href="http://www.learningjquery.com/2008/10/1-awesome-way-to-avoid-the-not-so-excellent-flash-of-amazing-unstyled-content">click here</a>.</p>
<p><a title="tip24" name="tip24"></a></p>
<h3>24. Return &#8216;false&#8217; to prevent default behaviour</h3>
<p>This should be an obvious one but maybe not.  if you have a habit of doing this&#8230;</p>
<pre class="xml">&lt;a href="#" class="popup"&gt;Click me!&lt;/a&gt;</pre>
<p>&#8230; and then attaching an event handler like this&#8230;</p>
<pre class="Jscript">$('popup').click(function(){     // Launch popup code });</pre>
<p>&#8230; it&#8217;ll probably work fine until you use it on a long page, at which point you&#8217;ll notice that the # is causing it to jump to the top of the page when your click event is triggered.</p>
<p>All you have to do to prevent this default behaviour, or indeed any default behaviour on any event handler is to add &#8220;return false;&#8221; to your handler, like this&#8230;</p>
<pre class="Jscript">$('popup').click(function(){     // Launch popup code     return false; });</pre>
<p><a title="tip25" name="tip25"></a></p>
<h3>25. Shorthand for the ready event</h3>
<p>A small tip this one but you can save a few characters by using shorthand for the $(document).ready function.</p>
<p>Instead of this&#8230;</p>
<pre class="Jscript">$(document).ready(function (){     // your code });</pre>
<p>You can do this&#8230;</p>
<pre class="Jscript">$(function (){     // your code });</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.simsekmert.com/wp/2009/04/25-excellent-jquery-tips/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

