<?xml version="1.0" encoding="utf-8"?>
    <feed xmlns="http://www.w3.org/2005/Atom">
     <title>BigBinary Blog</title>
     <link href="https://www.bigbinary.com/feed.xml" rel="self"/>
     <link href="https://www.bigbinary.com/"/>
     <updated>2026-03-06T02:37:31+00:00</updated>
     <id>https://www.bigbinary.com/</id>
     <entry>
       <title><![CDATA[jquery-ujs and jquery trigger]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger"/>
      <updated>2012-05-11T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger</id>
      <content type="html"><![CDATA[<p>Let's see how to make AJAX call using jquery.</p><p>jQuery's ajax method's <code>success</code> callback function takes three parameters. Hereis the <a href="http://api.jquery.com/jQuery.ajax/">api</a> .</p><pre><code class="language-javascript">success(data, textStatus, jqXHR);</code></pre><p>So if you are making ajax call using jQuery the code might look like</p><pre><code class="language-javascript">$.ajax({  url: &quot;ajax/test.html&quot;,  success: function (data, textStatus, jqXHR) {    console.log(data);  },});</code></pre><h2>ajax using jquery-ujs</h2><p>If you are using Rails and jquery-ujs then you might have code like this</p><pre><code class="language-plaintext">&lt;a href=&quot;/users/1&quot; data-remote=&quot;true&quot; data-type=&quot;json&quot;&gt;Show&lt;/a&gt;</code></pre><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;ajax:success&quot;, function (data, status, xhr) {  alert(data.name);});</code></pre><p>Above code will not work. In order to make it work the very first element passedto the callback must be an event object. Here is the code that will work.</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;ajax:success&quot;, function (event, data, status, xhr) {  alert(data.name);});</code></pre><p>Remember that jQuery api says that the first parameter should be &quot;data&quot; then whywe need to pass event object to make it work.</p><h2>Why event object is needed</h2><p>Here is snippet from jquery-ujs code</p><pre><code class="language-plaintext">success: function(data, status, xhr) {  element.trigger('ajax:success', [data, status, xhr]);}</code></pre><p>The thing about <a href="http://api.jquery.com/trigger/">trigger</a> method is that theevent object is always passed as the first parameter to the event handler. Thisis why when you are using jquery-ujs you have to have the first parameter in thecallback function an event object.</p>]]></content>
    </entry><entry>
       <title><![CDATA[An inline confirmation utility powered by jQuery]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/iconfirm-an-inline-confirmation-jquery-plugin"/>
      <updated>2010-11-02T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/iconfirm-an-inline-confirmation-jquery-plugin</id>
      <content type="html"><![CDATA[<p>I needed inline confirmation utility.</p><p>With jQuery it was easy.</p><p>After a few hours I had <code>iconfirm</code>.</p><p>This project is deprecated now.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Return false has changed in jquery 1.4.3]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/return-false-in-jquery-1.4.3"/>
      <updated>2010-10-25T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/return-false-in-jquery-1.4.3</id>
      <content type="html"><![CDATA[<p>jQuery 1.4.3 was recently<a href="http://blog.jquery.com/2010/10/16/jquery-143-released/">released</a>. If youupgrade to jQuery 1.4.3 you will notice that the behavior of <code>return false</code> haschanged in this version. First let's see what <code>return false</code> does.</p><h2>return false</h2><pre><code class="language-javascript">$(&quot;a&quot;).click(function () {  console.log(&quot;clicked&quot;);  return false;});</code></pre><p>First ensure that above code is executed on domready. Now if I click on any linkthen two things will happen.</p><pre><code class="language-plaintext">e.preventDefault() will be called .e.stopPropagation() will be called .</code></pre><h2>e.preventDefault()</h2><p>As the name suggests, calling <code>e.preventDefault()</code> will make sure that thedefault behavior is not executed.</p><pre><code class="language-plaintext">&lt;a href='www.google.com'&gt;click me&lt;/a&gt;</code></pre><p>If above link is clicked then the default behavior of the browser is to take youto <code>www.google.com</code>. However by invoking <code>e.preventDefault()</code> browser will notgo ahead with default behavior and I will &lt;strong&gt;not&lt;/strong&gt; be taken to<code>www.google.com</code>.</p><h2>e.stopPropagation</h2><p>When a link is clicked then an event &quot;click event&quot; is created. And this eventbubbles all the way up to the top. By invoking <code>e.stopPropagation</code> I am askingbrowser to not to propagate the event. In other words the event will stopbubbling.</p><pre><code class="language-html">&lt;div class=&quot;first&quot;&gt;  &lt;div class=&quot;two&quot;&gt;    &lt;a href=&quot;www.google.com&quot;&gt;click me&lt;/a&gt;  &lt;/div&gt;&lt;/div&gt;</code></pre><p>If I click on &quot;click me&quot; then &quot;click event&quot; will start bubbling. Now let's saythat I catch this event at <code>.two</code> and if I call <code>e.stopPropagation()</code> then thisevent will never reach to <code>.first</code> .</p><h2>e.stopImmediatePropagation</h2><p>First note that you can bind more than one event to an element. Take a look atfollowing case.</p><pre><code class="language-html">&lt;a class=&quot;one&quot;&gt;one&lt;/a&gt;</code></pre><p>I am going to bind three events to the above element.</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;click&quot;, function (e) {  console.log(&quot;first&quot;);});$(&quot;a&quot;).bind(&quot;click&quot;, function (e) {  console.log(&quot;second&quot;);  e.stopImmediatePropagation();});$(&quot;a&quot;).bind(&quot;click&quot;, function (e) {  console.log(&quot;third&quot;);});</code></pre><p>In this case there are three events bound to the same element. Notice thatsecond event binding invokes <code>e.stopImmediatePropagation()</code> . Calling<code>e.stopImmediatePropagation</code> does two things.</p><p>Just like <code>stopPropagation</code> it will stop the bubbling of the event. So anyparent of this element will not get this event.</p><p>However <code>stopImmdiatePropagation</code> stops the event bubbling even to the siblings.It kills the event right then and there. That's it. End of the event.</p><p>Once again calling <code>stopPropagation</code> means stop this event going to parent. Andcalling <code>stopImmediatePropagation</code> means stop passing this event to other eventhandlers bound to itself.</p><p>If you are interested<a href="http://www.w3.org/TR/2006/WD-DOM-Level-3-Events-20060413/events.html#Events-Event-stopImmediatePropagation">here is link to </a>DOM Level 3 Events spec.</p><h2>Back to original problem</h2><p>Now that I have described what <code>preventDefault</code>, <code>stopPropagation</code> and<code>stopImmediatePropagation</code> does lets see what changed in jQuery 1.4.3.</p><p>In jQuery 1.4.2 when I execute &quot;return false&quot; then that action was same asexecuting:</p><pre><code class="language-javascript">e.preventDefault();e.stopPropagation();e.stopImmediatePropagation();</code></pre><p>Now <code>e.stopImmediatePropagation</code> internally calls <code>e.stopPragation</code> but I haveadded here for visual clarity.</p><p>Fact that <code>return false</code> was calling <code>e.stopImmeidatePropagation</code> was a bug. Getthat. It was a bug which got fixed in jquery 1.4.3.</p><p>So in jquery 1.4.3 <code>e.stopImmediatePropagation</code> is not called. Checkout thispiece of code from <code>events.js</code> of jquery code base.</p><pre><code class="language-javascript">if (ret !== undefined) {  event.result = ret;  if (ret === false) {    event.preventDefault();    event.stopPropagation();  }}</code></pre><p>As you can see when <code>return false</code> is invoked then <code>e.stopImmediatePropagation</code>is &lt;strong&gt;not&lt;/strong&gt; called.</p><h2>It gets complicated with live and a bug in jQuery 1.4.3</h2><p>To make the case complicated, jQuery 1.4.3 has a bug in which<code>e.preventStopImmediatePropagation</code> doest not work. Here is<a href="http://forum.jquery.com/topic/e-stopimmedidatepropagation-does-not-work-with-live-or-with-delegate">a link to this bug</a>I reported.</p><p>To understand the bug take a look at following code:</p><pre><code class="language-plaintext">&lt;a href='' class='first'&gt;click me&lt;/a&gt;$('a.first').live('click', function(e){    alert('hello');    e.preventDefault();    e.stopImmediatePropagation();});$('a.first').live('click', function(){    alert('world');});</code></pre><p>Since I am invoking <code>e.stopImmediatePropagation</code> I should never see<code>alert world</code>. However you will see that alert if you are using jQuery 1.4.3.You can play with it <a href="http://jsbin.com/ujipi4/3#html">here</a> .</p><p>This bug has been fixed as per<a href="http://github.com/jquery/jquery/commit/974b5aeab7a3788ff5fb9db87b9567784e0249fc">this commit</a>. Note that the commit mentioned was done after the release of jQuery 1.4.3. Toget the fix you will have to wait for jQuery 1.4.4 release or use jQuery edge.</p><h2>I am using rails.js (jquery-ujs). What do I do?</h2><p>As I have shown &quot;return false&quot; does not work in jQuery 1.4.3 . However I wouldhave to like to have as much backward compatibility in <code>jquery-ujs</code> as muchpossible so that the same code base works with jQuery 1.4 through 1.4.3 sincenot every one upgrades immediately.</p><p><a href="http://github.com/rails/jquery-ujs/commit/f991faf0074487b43a061168cdbfd102ee0c182c">This commit</a>should make <code>jquery-ujs</code> jquery 1.4.3 compatible.<a href="http://github.com/rails/jquery-ujs/issues">Many issues</a> have been logged atjquery-ujs and I will take a look at all of them one by one. Please do provideyour feedback.</p>]]></content>
    </entry><entry>
       <title><![CDATA[List of only the elements that contains]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/list-of-only-the-elements"/>
      <updated>2010-04-12T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/list-of-only-the-elements</id>
      <content type="html"><![CDATA[<p>I was toying with<a href="http://kilianvalkhof.com/2010/javascript/how-to-build-a-fast-simple-list-filter-with-jquery">simple list filter plugin</a>and ended up with this markup.</p><pre><code class="language-html">&lt;div id=&quot;lab&quot;&gt;  &lt;ul id=&quot;list&quot;&gt;    &lt;li&gt;&lt;a href=&quot;&quot;&gt;USA&lt;/a&gt;&lt;/li&gt;  &lt;ul&gt;  &lt;p&gt;    &lt;a href=''&gt;USA&lt;/a&gt;  &lt;/p&gt;&lt;/div&gt;</code></pre><p>I want to get all links that contains the word <code>USA</code>. Simple enough. jQuerysupports <code>contains</code> selector.</p><pre><code class="language-javascript">$(&quot;:contains('USA')&quot;);</code></pre><p>Above query results in following items.</p><pre><code class="language-ruby">[html, body#body, div#lab, ul#list, li, a, ul, p, a]</code></pre><p>That is because <a href="http://api.jquery.com/contains-selector">contains</a> looks forgiven string under all the descendants.</p><h2>has method to rescue</h2><p>jQuery <a href="http://api.jquery.com/has">has</a> method which returns the list ofelements which have a descendant which has the given string.</p><pre><code class="language-javascript">b = $(&quot;*&quot;).has(&quot;:contains('USA')&quot;);</code></pre><p>Above query results in following items.</p><pre><code class="language-ruby">[html, body#body, div#lab, ul#list, li, ul, p]</code></pre><h2>Final result</h2><pre><code class="language-javascript">a = $(&quot;:contains('USA')&quot;);b = $(&quot;*&quot;).has(&quot;:contains('USA')&quot;);c = a.not(b);console.log(c);</code></pre><p>Above query results in following items.</p><pre><code class="language-ruby"> [a, a]</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[return false considered harmful in live]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/return-false-considered-harmful-in-live-jquery"/>
      <updated>2010-03-10T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/return-false-considered-harmful-in-live-jquery</id>
      <content type="html"><![CDATA[<p>Checkout following jQuery code written with jQuery.1.4.2. What do you think willhappen when first link is clicked.</p><pre><code class="language-javascript">$(&quot;a:first&quot;).live(&quot;click&quot;, function () {  log(&quot;clicked once&quot;);  return false;});$(&quot;a:first&quot;).live(&quot;click&quot;, function () {  log(&quot;clicked twice&quot;);  return false;});</code></pre><p>I was expecting that I would see both the messages. However jQuery only invokesthe very first message.</p><p><code>return false</code> does two things. It stops the default behavior which is go andfetch the link mentioned in the <code>href</code> of the anchor tags. Also it stops theevent from bubbling up. Since live method relies on event bubbling, it makessense that second message does not appear.</p><p>Fix is simple. Just block the default action but let the event bubble up.</p><pre><code class="language-javascript">$(&quot;a:first&quot;).live(&quot;click&quot;, function (e) {  log(&quot;clicked once&quot;);  e.preventDefault();});$(&quot;a:first&quot;).live(&quot;click&quot;, function (e) {  log(&quot;clicked twice&quot;);  e.preventDefault();});</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Simplest jQuery slideshow code explanation]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation"/>
      <updated>2010-02-18T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation</id>
      <content type="html"><![CDATA[<p><a href="http://snook.ca">Jonathan Snook</a> wrote a blog titled<a href="http://snook.ca/archives/javascript/simplest-jquery-slideshow">Simplest jQuery SlideShow</a>.Checkout the <a href="http://snook.ca/technical/fade/fade.html">demo page</a>. The fullJavaScript code in its entirety is given below. If you understand this code thenyou don't need to read rest of the article.</p><pre><code class="language-javascript">$(function () {  $(&quot;.fadein img:gt(0)&quot;).hide();  setInterval(function () {    $(&quot;.fadein :first-child&quot;)      .fadeOut()      .next(&quot;img&quot;)      .fadeIn()      .end()      .appendTo(&quot;.fadein&quot;);  }, 3000);});</code></pre><h2>appendTo removes and attaches elements</h2><p>In order to understand what's going on above, I am constructing a simple testpage. Here is the html markup.</p><pre><code class="language-html">&lt;div id=&quot;container&quot;&gt;  &lt;div class=&quot;lab&quot;&gt;This is div1&lt;/div&gt;  &lt;div class=&quot;lab&quot;&gt;This is div2&lt;/div&gt;&lt;/div&gt;</code></pre><p>Open this page in browser and execute following command in firebug.</p><pre><code class="language-javascript">$(&quot;.lab:first&quot;).appendTo(&quot;#container&quot;);</code></pre><p>Run the above command 5/6 times to see its effect. Every single time you runJavaScript the order is changing.</p><p>The order of <code>div</code> elements with class <code>lab</code> is changing because if a jQueryelement is already part of document and that element is being added somewhereelse then jQuery will do <code>cut and paste</code> and <em>not</em> <code>copy and paste</code> . Againelements that already exist in the document get plucked out of document and thenthey are inserted somewhere else in the document.</p><h2>Back to the original problem</h2><p>In the original code the very first image is being plucked out of document andthat image is being added to set again. In simpler terms this is what ishappening. Initially the order is like this.</p><pre><code class="language-plaintext">Image1Image2Image3</code></pre><p>After the code is executed the order becomes this.</p><pre><code class="language-plaintext">Image2Image3Image1</code></pre><p>After the code is executed again then the order becomes this.</p><pre><code class="language-plaintext">Image3Image1Image2</code></pre><p>After the code is executed again then the order becomes this.</p><pre><code class="language-plaintext">Image1Image2Image3</code></pre><p>And this cycle continues forever.</p>]]></content>
    </entry><entry>
       <title><![CDATA[How jQuery selects elements using Sizzle]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/how-jquery-selects-elements-using-sizzle"/>
      <updated>2010-02-15T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/how-jquery-selects-elements-using-sizzle</id>
      <content type="html"><![CDATA[<p>jQuery's motto is to select something and do something with it. As jQuery users,we provide the selection criteria and then we get busy with doing something withthe result. This is a good thing. jQuery provides extremely simple API forselecting elements. If you are selecting ids then just prefix the name with '#'.If you are selecting a class then prefix it with '.'.</p><p>However it is important to understand what goes on behind the scene for manyreasons. And one of the important reasons is the performance of Rich Client. Asmore and more web pages use more and more jQuery code, understanding of howjQuery selects elements will speed up the loading of pages.</p><h2>What is a selector engine</h2><p>HTML documents are full of html markups. It's a tree like structure. Ideallyspeaking all the html documents should be 100% valid xml documents. However ifyou miss out on closing a div then browsers forgive you ( unless you have askedfor strict parsing). Ultimately browser engine sees a well formed xml document.Then the browser engine renders that xml on the browser as a web page.</p><p>After a page is rendered then those xml elements are referred as DOM elements.</p><p>JavaScript is all about manipulating this tree structure (DOM elements) thatbrowser has created in memory. A good example of manipulating the tree iscommand like the one give below which would hide the header element. However inorder to hide the header tag, jQuery has to get to that DOM element.</p><pre><code class="language-javascript">jQuery(&quot;#header&quot;).hide();</code></pre><p>The job of a selector engine is to get all the DOM elements matching thecriteria provided by a user. There are many JavaScript selector engines in themarket. Paul Irish has<a href="http://paulirish.com/2008/javascript-css-selector-engine-timeline">a nice article</a>about JavaScript CSS Selector Engine timeline .</p><p><a href="http://sizzlejs.com">Sizzle</a> is JavaScript selector engine developed by<a href="http://ejohn.org">John Resig</a> and is used internally in jQuery. In this articleI will be showing how jQuery in conjunction with Sizzle finds elements.</p><h2>Browsers help you to get to certain elements</h2><p>Browsers do provide some helper functions to get to certain types of elements.For example if you want to get DOM element with id <code>header</code> then<code>document.getElementById</code> function can be used like this</p><pre><code class="language-javascript">document.getElementById(&quot;header&quot;);</code></pre><p>Similarly if you want to collect all the p elements in a document then you coulduse following code .</p><pre><code class="language-javascript">document.getElementsByTagName(&quot;p&quot;);</code></pre><p>However if you want something complex like the one given below then browserswere not much help. It was possible to walk up and down the tree howevertraversing the tree was tricky because of two reasons: a) DOM spec is not veryintuitive b) Not all the browsers implemented DOM spec in same way.</p><pre><code class="language-javascript">jQuery(&quot;#header a&quot;);</code></pre><p>Later <a href="http://www.w3.org/TR/selectors-api">selector API</a> came out.</p><p>The latest version of all the major browsers support this specificationincluding IE8. However IE7 and IE6 do not support it. This API provides<code>querySelectorAll</code> method which allows one to write complex selector query like<code>document.querySelectorAll(&quot;#score&gt;tbody&gt;tr&gt;td:nth-of-type(2)&quot;</code> .</p><p>It means that if you are using IE8 or current version of any other modernbrowser then jQuery code <code>jQuery('#header a')</code> will not even hit Sizzle. Thatquery will be served by a call to <code>querySelectorAll</code> .</p><p>However if you are using IE6 or IE7, Sizzle will be invoked for jQuery('#headera'). This is one of the reasons why some apps perform much slower on IE6/7compared to IE8 since a native browser function is much faster than elementsretrieval by Sizzle.</p><h2>Selection process</h2><p>jQuery has a lot of optimization baked in to make things run faster. In thissection I will go through some of the queries and will try to trace the routejQuery follows.</p><h2>$('#header')</h2><p>When jQuery sees that the input string is just one word and is looking for an idthen jQuery invokes document.getElementById . Straight and simple. Sizzle is notinvoked.</p><h2>$('#header a') on a modern browser</h2><p>If the browser supports querySelectorAll then querySelectorAll will satisfy thisrequest. Sizzle is not invoked.</p><h2>$('.header a[href!=&quot;hello&quot;]') on a modern browser</h2><p>In this case jQuery will try to use querySelectorAll but the result would be anexception (at least on firefox). The browser will throw an exception because thequerySelectorAll method does not support certain selection criteria. In thiscase when browser throws an exception, jQuery will pass on the request toSizzle. Sizzle not only supports css 3 selector but it goes above and beyondthat.</p><h2>$('.header a') on IE6/7</h2><p>On IE6/7 <code>querySelectorAll</code> is not available so jQuery will pass on this requestto Sizzle. Let's see a little bit in detail how Sizzle will go about handlingthis case.</p><p>Sizzle gets the selector string '.header a'. It splits the string into two partsand stores in variable called parts.</p><pre><code class="language-javascript">parts = [&quot;.header&quot;, &quot;a&quot;];</code></pre><p>Next step is the one which sets Sizzle apart from other selector engines.Instead of first looking for elements with class <code>header</code> and then going down,Sizzle starts with the outer most selector string. As per<a href="https://www.paulirish.com/2009/perf/">this presentation</a> from Paul Irish<a href="https://yuilibrary.com/">YUI3</a> and NWMatcher (Link is not available) also goright to left.</p><p>So in this case Sizzle starts looking for all <code>a</code> elements in the document.Sizzle invokes the method <code>find</code>. Inside the find method Sizzle attempts to findout what kind of pattern this string matches. In this case Sizzle is dealingwith string <code>a</code> .</p><p>Here is snippet of code from Sizzle.find .</p><pre><code class="language-plaintext">match: {     ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,     CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,     NAME: /\[name=['&quot;]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['&quot;]*\]/,     ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['&quot;]*)(.*?)\3|)\s*\]/,     TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,     CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,     POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,     PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['&quot;]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},</code></pre><p>One by one Sizzle will go through all the match definitions. In this case since<code>a</code> is a valid tag, a match will be found for <code>TAG</code>. Next following functionwill be called.</p><pre><code class="language-plaintext">TAG: function(match, context){     return context.getElementsByTagName(match[1]);}</code></pre><p>Now result consists of all <code>a</code> elements.</p><p>Next task is to find if each of these elements has a parent element matching<code>.header</code>. In order to test that a call will be made to method <code>dirCheck</code>. Inshort this is what the call looks like.</p><pre><code class="language-javascript">dir = 'parentNode';cur = &quot;.header&quot;checkSet = [ a www.neeraj.name, a www.google.com ] // object representationdirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML )</code></pre><p>dirCheck method returns whether each element of checkSet passed the test. Afterthat a call is made to method <code>preFilter</code>. In this method the key code is below</p><pre><code class="language-javascript">if ( not ^ (elem.className &amp;&amp; (&quot; &quot; + elem.className + &quot; &quot;).replace(/[\t\n]/g, &quot; &quot;).indexOf(match) &gt;= 0) )</code></pre><p>For our example this is what is being checked</p><pre><code class="language-javascript">&quot; header &quot;.indexOf(&quot; header &quot;);</code></pre><p>This operation is repeated for all the elements on the checkSet. Elements notmatching the criteria are rejected.</p><h2>More methods in Sizzle</h2><p>if you dig more into Sizzle code you would see functions defined as <code>+</code>, <code>&gt;</code> and<code>~</code> . Also you will see methods like</p><pre><code class="language-plaintext">enabled: function(elem) {          return elem.disabled === false &amp;&amp; elem.type !== &quot;hidden&quot;;    },disabled: function(elem) {          return elem.disabled === true;     },checked: function(elem) {          return elem.checked === true;     },selected: function(elem) {          elem.parentNode.selectedIndex;          return elem.selected === true;     },parent: function(elem) {          return !!elem.firstChild;     },empty: function(elem) {          return !elem.firstChild;     },has: function(elem, i, match) {          return !!Sizzle( match[3], elem ).length;     },header: function(elem) {          return /h\d/i.test( elem.nodeName );     },text: function(elem) {          return &quot;text&quot; === elem.type;     },radio: function(elem) {          return &quot;radio&quot; === elem.type;     },checkbox: function(elem) {          return &quot;checkbox&quot; === elem.type;     },file: function(elem) {          return &quot;file&quot; === elem.type;     },password: function(elem) {          return &quot;password&quot; === elem.type;     },submit: function(elem) {          return &quot;submit&quot; === elem.type;     },image: function(elem) {          return &quot;image&quot; === elem.type;     },reset: function(elem) {          return &quot;reset&quot; === elem.type;     },button: function(elem) {          return &quot;button&quot; === elem.type || elem.nodeName.toLowerCase() === &quot;button&quot;;     },input: function(elem) {          return /input|select|textarea|button/i.test(elem.nodeName);     }},first: function(elem, i) {          return i === 0;     },last: function(elem, i, match, array) {          return i === array.length - 1;     },even: function(elem, i) {          return i % 2 === 0;     },odd: function(elem, i) {          return i % 2 === 1;     },lt: function(elem, i, match) {          return i &lt; match[3] - 0;     },gt: function(elem, i, match) {          return i &gt; match[3] - 0;     },nth: function(elem, i, match) {          return match[3] - 0 === i;     },eq: function(elem, i, match) {          return match[3] - 0 === i;     }</code></pre><p>I use all these methods almost daily and it was good to see how these methodsare actually implemented.</p><h2>Performance Implications</h2><p>Now that I have little more understanding of how Sizzle works, I can betteroptimize my selector queries. Here are two selectors doing the same thing.</p><pre><code class="language-javascript">$(&quot;p.about_me .employment&quot;);$(&quot;.about_me  p.employment&quot;);</code></pre><p>Since Sizzle goes from right to left, in the first case Sizzle will pick up allthe elements with the class <code>employment</code> and then Sizzle will try to filter thatlist. In the second case Sizzle will pick up only the <code>p</code> elements with class<code>employment</code> and then it will filter the list. In the second case the right mostselection criteria is more specific and it will bring better performance.</p><p>So the rule with Sizzle is to go more specific on right hand side and to go lessspecific on left hand side. Here is another example.</p><pre><code class="language-javascript">$(&quot;.container :disabled&quot;);$(&quot;.container input:disabled&quot;);</code></pre><p>The second query will perform better because the right side query is morespecific.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Understanding jQuery effects queue]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/understanding-jquery-effects-queue"/>
      <updated>2010-02-02T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/understanding-jquery-effects-queue</id>
      <content type="html"><![CDATA[<p>Recently I tried following code in jQuery and it did not work.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }).hide();</code></pre><p>If I pass a parameter to <code>hide</code> then it would start working.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }).hide(1);</code></pre><p>As it turns out I did not have proper understanding of how effects work injQuery.</p><p>animate method uses a queue inside. This is the queue to which all the pendingactivities are added.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }).animate({ width: &quot;200px&quot; });</code></pre><p>In the above code element is being animated twice. However the second animationwill not start until the first animation is done. While the first animation ishappening the second animation is added to a queue. Name of this default queueis <code>fx</code>. This is the queue to which jQuery adds all the pending activities whileone activity is in progress. You can inquire an element about how many pendingactivities are there in the queue.</p><pre><code class="language-javascript">$(&quot;#lab&quot;)  .animate({ height: &quot;200px&quot; })  .animate({ width: &quot;200px&quot; })  .animate({ width: &quot;800px&quot; })  .queue(function () {    console.log($(this).queue(&quot;fx&quot;).length);    $(this).dequeue();  })  .animate({ width: &quot;800px&quot; })  .queue(function () {    console.log($(this).queue(&quot;fx&quot;).length);    $(this).dequeue();  });</code></pre><p>In the above code, twice the current queue is being asked to list number ofpending activities. First time the number of pending activities is 3 and thesecond time it is 1.</p><p>Method show and hide also accepts duration. If a duration is passed then thatoperation is added to the queue. If duration is not passed or if the duration iszero then that operation is not added to queue.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).hide(); // this action is not added to fx queue$(&quot;#lab&quot;).hide(0); // this action is not added to fx queue$(&quot;#lab&quot;).hide(1); // this action is added to fx queue</code></pre><h2>Coming back to the original question</h2><p>When show or hide method is invoked without any duration then those actions arenot added to queue.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }).hide();</code></pre><p>In the above code since hide method is not added to queue, both the animate andthe hide method are executed simultaneously. Hence the end result is thatelement is not hidden.</p><p>It could be fixed in a number of ways. One way would be to pass a duration tohide method.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }).hide(1);</code></pre><p>Another way to fix it would be to pass hiding action as a callback function toanimate method.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }, function () {  $(this).hide();});</code></pre><p>Another way would be to explicitly put hide method in a queue.</p><pre><code class="language-javascript">$(&quot;#lab&quot;)  .animate({ height: &quot;200px&quot; })  .queue(function () {    $(this).hide();  });</code></pre><p>Since hide method is not added to queue by default, in this case I haveexplicitly put the hide method to the queue.</p><p>Note that inside a queue method you must explicitly call <code>dequeue</code> for the nextactivity from the queue to be picked up.</p><pre><code class="language-javascript">$(&quot;#lab&quot;)  .animate({ height: &quot;200px&quot; })  .queue(function () {    $(this).hide().dequeue();  })  .animate({ width: &quot;200px&quot; });</code></pre><p>In the above code if <code>dequeue</code> is not called then second animation will nevertake place.</p><p>Also note that methods like fadeTo, fadeIn, fadeOut, slideDown, slideUp andanimate are ,by default, added to default queue.</p><h2>Turning off all animations</h2><p>If for some reason you don't want animation then just set <code>$.fx.off = true</code>.</p><pre><code class="language-javascript">$.fx.off = true;$(&quot;#lab&quot;).animate({ height: &quot;200px&quot; }, function () {  $(this).hide();});</code></pre><p>Above code is telling jQuery to turn off all animations and that would result inthe element hiding in an instant.</p>]]></content>
    </entry><entry>
       <title><![CDATA[jQuery edge delegate method has arrived]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-edge-delegate-method-has-arrived"/>
      <updated>2010-02-02T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-edge-delegate-method-has-arrived</id>
      <content type="html"><![CDATA[<p>One of the issues with live method is that live method first searches throughall the elements then throws away the result.</p><pre><code class="language-javascript">$('p').live('click', function({})</code></pre><p>In the above case jQuery does nothing with the selected <code>p</code> elements. Since theresult does not really matter, it is a good idea to remove such codes from the<code>document ready</code> callbacks list.</p><p>So instead of doing this</p><pre><code class="language-javascript">$(function(){  $('p').live('click', function({})})</code></pre><p>just do this</p><pre><code class="language-javascript">$('p').live('click', function({})</code></pre><h2>Going a step further</h2><p>John just landed<a href="http://github.com/jquery/jquery/commit/31432e048f879b93ffa44c39d6f5989ab2620bd8#comments">this commit which adds delegate</a>method .</p><p>Html markup</p><pre><code class="language-html">&lt;div id=&quot;lab&quot;&gt;  &lt;p&gt;p inside lab&lt;/p&gt;&lt;/div&gt;&lt;p&gt;p outside lab&lt;/p&gt;</code></pre><p>If you want to track all the clicks on p then you could write like this.</p><pre><code class="language-javascript">$(document).delegate(&quot;p&quot;, &quot;click&quot;, function () {  log(&quot;p was clicked&quot;);});</code></pre><p>However if you only want to track clicks on 'p' which are inside the id <code>lab</code>then you can write like this.</p><pre><code class="language-javascript">$(&quot;#lab&quot;).delegate(&quot;p&quot;, &quot;click&quot;, function () {  log(&quot;p was clicked&quot;);});</code></pre><p>Note this functionality is in jQuery edge and is not available in jQuery 1.4.1.So you will have to get jQuery code from github to play with it.</p><p>If you are interested in the jQuery.live vs jQuery.fn.live discussion thenfollow<a href="http://forum.jquery.com/topic/jquery-live-jquery-fn-live-discussion">this thread</a>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[jQuery show method edge case]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-show-method-edge-case"/>
      <updated>2010-01-29T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-show-method-edge-case</id>
      <content type="html"><![CDATA[<p>Here is a simple case of invoking <code>show</code> method on a hidden element.</p><pre><code class="language-html">&lt;style&gt;  p {    display: inline;  }  #hello p {    display: none;  }&lt;/style&gt;&lt;div id=&quot;container&quot;&gt;  &lt;div id=&quot;hello&quot;&gt;    Hello World    &lt;p&gt;this is p inside hello&lt;/p&gt;  &lt;/div&gt;&lt;/div&gt;</code></pre><p>jQuery code.</p><pre><code class="language-javascript">$(&quot;p&quot;).show();</code></pre><p>You can see the result <a href="http://jsfiddle.net/d5uW7">here</a> . Notice that when <code>p</code>is shown then <code>display</code> property of <code>p</code> is <code>inline</code> which is what it should be.All is well.</p><p>Now I'll change the css a little bit and will try the same code again. New cssis .</p><pre><code class="language-html">&lt;style&gt;  #container p {    display: inline;  }  #hello p {    display: none;  }&lt;/style&gt;</code></pre><p>See the result <a href="http://jsfiddle.net/qj6PT">here</a> . Notice that <code>display</code>property of <code>p</code> is <code>block</code> instead of <code>inline</code> .</p><h2>Where did jQuery go wrong?</h2><p>jQuery did not do anything wrong. It is just being a bit lazy. I'll explain.</p><p>Since the element was hidden when jQuery was asked to display it, jQuery had noidea where the element should have display property <code>inline</code> or <code>block</code>. SojQuery attempts to find out the display property of the element by askingbrowser what the display property should be.</p><p>jQuery first finds out the nodeName of the element. In this case value would be<code>P</code>. Then jQuery adds a <code>P</code> to body and then asks browser what is the displayproperty of this newly added element. Whatever is the return value jQueryapplies that value to the element that was asked to be shown.</p><p>In the first experiment, css style <code>p { display: inline; }</code>said that all pelements are inline. So when jQuery added a new p element to body and askedbrowser for the display property, browser replied 'inline' and 'inline' wasapplied to the element. All was good.</p><p>In the second case, I changed the stylesheet <code>#container p { display: inline; }</code>to have only p elements under id <code>hello</code> to have inline property. So when jQueryadded a p element to body and asked for display type, browser correctly repliedas 'block'.</p><p>So what's the fix.</p><p>Find the parent element (#hello) of the element in question ( p in this case) .jQuery should add a new p element to the #hello and then jQuery would get theright display property.</p>]]></content>
    </entry><entry>
       <title><![CDATA[jQuery fadeTo method fades even the hidden elements]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-fadeto-method-fades-even-the-hidden-elements"/>
      <updated>2010-01-29T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-fadeto-method-fades-even-the-hidden-elements</id>
      <content type="html"><![CDATA[<p><em>Following code has been tested with jQuery 1.4.1 . Code demo links are the endof the blog .</em></p><p><a href="http://api.jquery.com/fadeTo">fadeTo</a> method of jQuery ,strangely, fades eventthe hidden elements.</p><p>Here is html markup.</p><pre><code class="language-html">&lt;style&gt;  #hello p {    display: none;  }&lt;/style&gt;&lt;div id=&quot;hello&quot;&gt;  &lt;p&gt;this is p inside hello&lt;/p&gt;&lt;/div&gt;&lt;p&gt;This is p outside hello&lt;/p&gt;</code></pre><p>Since the first <code>p</code> is hidden, you will see only one <code>p</code> element in the browser.Now execute following jQuery code.</p><pre><code class="language-javascript">$('p').fadeTo('slow', 0.5');</code></pre><p>You will see both the <code>p</code> elements.</p><p>jQuery goes out of its way to make sure that hidden elements are visible. Hereis <code>fadeTo</code> method.</p><pre><code class="language-javascript">fadeTo: function( speed, to, callback ) {return this.filter(&quot;:hidden&quot;).css(&quot;opacity&quot;, 0).show().end().animate({opacity: to}, speed, callback);}</code></pre><p>Also notice that for a hidden element fadeTo operation starts with opacity ofzero, while other elements will go down towards zero.</p><p>Checkout the same demo in slow motion and notice that while the first p elementemerges out of hiding, the other p element is slowing fading. This might causeunwanted effect . So watch out for this one.</p><ul><li><a href="http://jsfiddle.net/DPWSQ">First Demo</a></li><li><a href="http://jsfiddle.net/6gaEQ">Second Demo</a></li><li><a href="http://jsfiddle.net/sLwx5">Third Demo</a></li></ul>]]></content>
    </entry><entry>
       <title><![CDATA[How animate really works in jQuery]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/how-animate-really-works-in-jquery-simple-animation-case-discussed"/>
      <updated>2010-01-25T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/how-animate-really-works-in-jquery-simple-animation-case-discussed</id>
      <content type="html"><![CDATA[<p>jQuery has <a href="http://api.jquery.com/animate">animate method</a> which is justawesome. Today I looked into jQuery source code to see exactly how animateworks.</p><p>I will take a simple case of animating a <code>div</code> from height of <code>34</code> to <code>100</code>.</p><p>Here is test case.</p><pre><code class="language-javascript">$(function () {  $(&quot;#lab&quot;).css({ background: &quot;yellow&quot;, height: &quot;34px&quot;, margin: &quot;10px&quot; });  $(&quot;a&quot;).click(function () {    $(&quot;#lab&quot;).animate({ height: &quot;100&quot; });    return false;  });});</code></pre><p>Html markup is .</p><pre><code class="language-html">&lt;a href=&quot;&quot;&gt;click me&lt;/a&gt;&lt;div id=&quot;lab&quot;&gt;Hello World&lt;/div&gt;</code></pre><p>Inside the <code>animate</code> for each property an fx object is created.</p><pre><code class="language-javascript">jQuery.each( prop, function( name, val ) {  var e = new jQuery.fx( self, opt, name );}</code></pre><p>Calling new on jQuery.fx returns a JavaScript object instance.</p><pre><code class="language-javascript">fx: function( elem, options, prop ) {this.options = options;this.elem = elem;this.prop = prop;if ( !options.orig ) {options.orig = {};}}</code></pre><p>Next in the animate method is a call to <code>e.custom</code> .</p><pre><code class="language-javascript">start = 34;end = 100;unit = &quot;px&quot;;e.custom(start, end, unit);</code></pre><p>start, end and unit values are gleaned from the current state of div.</p><p>Here is custom method .</p><pre><code class="language-javascript">custom: function( from, to, unit ) {this.startTime = now();this.start = from;this.end = to;this.unit = unit || this.unit || &quot;px&quot;;this.now = this.start;this.pos = this.state = 0;var self = this;function t( gotoEnd ) {return self.step(gotoEnd);}t.elem = this.elem;if ( t() &amp;&amp; jQuery.timers.push(t) &amp;&amp; !timerId ) {timerId = setInterval(jQuery.fx.tick, 13);}},</code></pre><p>As you can see every 13 milliseconds a call to <code>step</code> method is made.</p><p><code>step</code> method is where real calculation is done. Here is the code.</p><pre><code class="language-javascript">step: function( gotoEnd ) {  var t = now();  var n = t - this.startTime;  this.state = n / this.options.duration;  pos = jQuery.easing['swing'](this.state, n, 0, 1, this.options.duration);  this.now = this.start + ((this.end - this.start) * this.pos);  this.update();}</code></pre><p><code>this.startTime</code> is the time when the call to <code>animate</code> was invoked. The <code>step</code>method is called periodically from custom method. So the value of <code>t</code> isconstantly changing. Based on the value of <code>t</code>, value of <code>n</code> will change. Someof the values of <code>n</code> I got was 1, 39, 69, 376 and 387.</p><p>While invoking animate method I did not specify a speed. jQuery picked up thedefault speed of 400. In this case the value of this.options.duration is <code>400</code>.The value of state would change in each run and it would something along theline of 0.0025, 0.09, 0.265, 0.915 and 0.945 .</p><p>If you don't know what easing is then you should read<a href="http://www.learningjquery.com/2009/02/quick-tip-add-easing-to-your-animations">this article</a>by Brandon Aaron. Since I did not specify easing option, jQuery will pickup<code>swing</code> easing .</p><p>In order to get the value of next position this easing algorithm needs state, nand duration. When all of it was supplied then <code>pos</code> would be derived. The valueof <code>pos</code> over the period of animation would change and it would be somethinglike 0, 0.019853157161528467, 0.04927244144387716, 0.9730426794137726,0.9973960708808632.</p><p>Based on the value of <code>pos</code> value of <code>now</code> is derived. And then <code>update</code> methodis called to update the screen.</p><p><code>update</code> method has following code that invokes <code>_default</code> method.</p><pre><code class="language-javascript">jQuery.fx.step._default)( this )</code></pre><p><code>_default</code> method has following code which finally updates the element.</p><pre><code class="language-javascript">fx.elem.style[fx.prop] = Math.max(0, fx.now);</code></pre><p>fx.now value was set in the custom method and here that value was actuallyapplied to the element.</p><p>You will have much better understanding of how animate works if you look at thesource code. I just wanted to know at a high level what's going on and these aremy findings.</p>]]></content>
    </entry><entry>
       <title><![CDATA[JSON parsing natively in jQuery 1.4 and updates]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3"/>
      <updated>2010-01-15T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3</id>
      <content type="html"><![CDATA[<p>With the popularity of JavaScript JSON has become very very popular.<a href="http://www.json.org">JSON</a> which stands for <code>JavaScript Object Notation</code> is apopular way to send and receive data between browser and server.</p><p>jQuery makes it extremely easy to deal with JSON data. In the below exampleserver sends a success message to browser. The JSON data looks like this.</p><pre><code class="language-text">{ 'success': 'record was successfully updated' }</code></pre><p>The jQuery code to handle JSON data looks like this.</p><pre><code class="language-javascript">$.ajax({  type: &quot;GET&quot;,  url: &quot;test.js&quot;,  dataType: &quot;json&quot;,  success: function (json) {    $(&quot;#result&quot;).text(json.success);  },});</code></pre><p>It all looks good and the code works with jQuery 1.3 .</p><p>However if you upgrade to jQuery 1.4 then above code will stop working. Why?jQuery 1.4 does strict JSON parsing using native parse method and any malformedJSON structure will be rejected.</p><h2>How jQuery 1.3 parses JSON structure</h2><p>jQuery 1.3 uses JavaScripts eval to evaluate incoming JSON structure. Openfirebug and type following example.</p><pre><code class="language-javascript">s = &quot; { 'success' :  'record was updated' } &quot;;result = eval(&quot;(&quot; + s + &quot;)&quot;);console.log(result);</code></pre><p>You will get a valid output.</p><p>Note that all valid JSON structure is also valid JavaScript code so evalconverts a valid JSON structure into a JavaScript object. However non JSONstructure can also be converted into JavaScript object.</p><p>JSON specification says that all string values must use double quotes. Singlequotes are not allowed. What it means is that following JSON structures are notvalid JSON.</p><pre><code class="language-text">{ 'foo' : 'bar' }{ foo: 'bar' }{ foo: &quot;bar&quot; }{ &quot;foo&quot; : 'bar' }</code></pre><p>Even though above strings are not valid JSON if you eval them they will producea valid JavaScript object. Since jQuery 1.3 uses eval on strings to convert JSONstructure to JavaScript object all the above mentioned examples work.</p><p>However they will not work if you upgrade to jQuery 1.4 .</p><h2>jQuery 1.4 uses native JSON parsing</h2><p>Using eval to convert JSON into JavaScript object has a few issue. First is thesecurity. It is possible that eval could execute some malicious code. Secondlyit is not as fast as native parse methods made available by browsers. Howeverbrowsers adhere to JSON spec and they will not parse malformed JSON structures.Open firebug and try following code to see how native browser methods do notparse malformed JSON structure. Here is the link to the announcement of<a href="http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31">Firefox support for native JSON parsing</a>. John Resig mentioned the need for jQuery to have native JSON parsing support<a href="http://ejohn.org/blog/native-json-support-is-required/#postcomment">here</a> .</p><pre><code class="language-javascript">s = &quot; { 'success' :  'record was updated' } &quot;;result = eval(&quot;(&quot; + s + &quot;)&quot;);console.log(result); /* returns valid JavaScript object */result2 = window.JSON.parse(s);console.log(result2); /* throws error */</code></pre><p>As you can see a string which was successfully parsed by <code>eval</code> failed by<code>window.JSON.parse</code> . It might or might not fail in chrome. More on that later.Since jQuery 1.4 will rely on browsers parsing the JSON structure malformed JSONstructures will fail.</p><p>In order to ensure that JSON is correctly parsed by the browsers, jQuery doessome code cleanup to make sure that you are not trying to pass somethingmalicious. You will not be able to test this thing directly using firebug but ifyou make an AJAX request and from server if you send response then you canverify the following code.</p><p>Following JSON structure will be correctly parsed in jQuery 1.3 . However thesame JSON structure will fail in jQuery 1.4 . Why? Because of dangling openbracket <code>[</code> .</p><pre><code class="language-javascript">' { &quot;error&quot; : &quot;record was updated&quot; }';</code></pre><p>jQuery 1.4 has following code that does some data cleanup to get around thesecurity issue with JSON parsing before sending that data to browser forparsing. Here is a snippet of the code.</p><pre><code class="language-javascript">// Make sure the incoming data is actual JSON// Logic borrowed from http://json.org/json2.jsif (/^[\],:{}\s]*$/.test(data.replace(/\\(?:[&quot;\\\/bfnrt]|u[0-9a-fA-F]{4})/g, &quot;@&quot;).replace(/&quot;[^&quot;\\\n\r]*&quot;|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, &quot;]&quot;).replace(/(?:^|:|,)(?:\s*\[)+/g, &quot;&quot;)))</code></pre><p>Not all browsers parse JSON same way</p><p>Earlier I mentioned that following JSON structure will not be correctly parsedby browsers.</p><pre><code class="language-text"> { 'a':1 } </code></pre><p>All browsers will fail to parse above JSON structure except <code>chrome</code> . Look atthis blog titled <a href="http://dbj.org/dbj/?p=470">Cross Browser JSON parsing</a> to getmore insight into this issue.</p><h2>I have malformed JSON and I want to use jQuery 1.4</h2><p>If you have malformed JSON and you want to use jQuery 1.4 then you should sendthe datatype as <code>text</code> and then convert the returned JSON structure using eval.Here is one way you can do that.</p><pre><code class="language-javascript">$.ajax({  url: &quot;/url&quot;,  dataType: &quot;text&quot;,  success: function (data) {    json = eval(&quot;(&quot; + data + &quot;)&quot;);    // do something with json  },});</code></pre><p><a href="http://benalman.com">Ben Alman</a> suggested another way in the<a href="http://yehudakatz.com/2010/01/15/jquery-1-4-and-malformed-json">comment section</a>.</p><pre><code class="language-text">/* this should be the very first JavaScript inclusion file */&lt;script type=text/javascript language=javascript&gt;window.JSON = null;&lt;/script&gt;</code></pre><p>jQuery attempts to parse JSON natively. However if native JSON parsing is notavailable then it falls back to <code>eval</code>. Here by setting <code>window.JSON to null</code>browser is faking that it does not have support for native JSON parsing.</p><p>Here are the<a href="http://github.com/jquery/jquery/commit/90a87c03b4943d75c24bc5e6246630231d12d933">two</a><a href="http://github.com/jquery/jquery/commit/44e6beb10304789044de2c5a58f5bb82e8321636">commits</a>which made most of the changes in the way parsing is done.</p><p>Use <a href="http://www.jsonlint.com">JSONLint</a> if you want to play with various stringsto see which one is valid JSON and which one is not.</p>]]></content>
    </entry><entry>
       <title><![CDATA[How jQuery 1.4 fixed rest of live methods]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/how-jquery-1-4-fixed-rest-of-live-methods"/>
      <updated>2010-01-14T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/how-jquery-1-4-fixed-rest-of-live-methods</id>
      <content type="html"><![CDATA[<p>If you look at jQuery 1.3 documentation for <code>live</code> method you will notice thatthe live method is not supported for following events: blur, focus, mouseenter,mouseleave, change and submit .</p><p>jQuery 1.4 fixed them all.</p><p>In this article I am going to discuss how jQuery brought support for thesemethods in jQuery. If you want a little background on what is <code>live</code> method andhow it works then you should read<a href="how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery">this article</a>which I wrote sometime back.</p><h3>focus and blur events</h3><p>IE and other browsers do not bubble <code>focus</code> and <code>blur</code> events. And that is incompliance with the w3c events model. As per the<a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-eventgroupings-htmlevents-h3">spec</a>focus event and blur event do not bubble.</p><p>However the spec also mentions two additional events called <code>DOMFocusIn</code> and<code>DOMFocusOut</code>. As per the<a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event-initUIEvent">spec</a>these two events should bubble. Firefox and other browsers implementedDOMFocusIn/DOMFocusOut . However IE implemented <code>focusin</code> and <code>focusout</code> and IEmade sure that these two events do bubble up.</p><p>jQuery team decided to pick shorter name and introduced two new events:<code>focusin</code> and <code>focusout</code>. These two events bubble and hence they can be usedwith live method.<a href="http://github.com/jquery/jquery/commit/03481a52c72e417b01cfeb499f26738cf5ed5839">This commit</a>makes focusin/focusout work with live method. Here is code snippet.</p><pre><code class="language-javascript">if (document.addEventListener) {  jQuery.each({ focus: &quot;focusin&quot;, blur: &quot;focusout&quot; }, function (orig, fix) {    jQuery.event.special[fix] = {      setup: function () {        this.addEventListener(orig, handler, true);      },      teardown: function () {        this.removeEventListener(orig, handler, true);      },    };    function handler(e) {      e = jQuery.event.fix(e);      e.type = fix;      return jQuery.event.handle.call(this, e);    }  });}</code></pre><p>Once again make sure that you are using <code>focusin/focusout</code> instead of<code>focus/blur</code> when used with <code>live</code> .</p><h2>mouseenter and mouseleave events</h2><p><code>mouseenter</code> and <code>mouseleave</code> events do not bubble in IE. However <code>mouseover</code>and <code>mouseout</code> do bubble in IE. If you are not sure of what the difference isbetween <code>mouseenter</code> and <code>mouseover</code> then<a href="http://www.bennadel.com/blog/1805-jQuery-Events-MouseOver-MouseOut-vs-MouseEnter-MouseLeave.htm">watch this excellent</a>screencast by Ben.</p><p>The fix that was applied to map for <code>focusin</code> can be replicated here to fix<code>mousetner</code> and <code>mouseleave</code> issue.<a href="http://github.com/jquery/jquery/commit/d251809912c06478fd0c7711736ef6ea3572723e">This is the commit</a>that fixed mouseenter and mouseleave issue with live method.</p><pre><code class="language-javascript">jQuery.each(  {    mouseenter: &quot;mouseover&quot;,    mouseleave: &quot;mouseout&quot;,  },  function (orig, fix) {    jQuery.event.special[orig] = {      setup: function (data) {        jQuery.event.add(          this,          fix,          data &amp;&amp; data.selector ? delegate : withinElement,          orig        );      },      teardown: function (data) {        jQuery.event.remove(          this,          fix,          data &amp;&amp; data.selector ? delegate : withinElement        );      },    };  });</code></pre><h2>Event detection</h2><p>Two more events are left to be handled: submit and change. Before jQuery appliesfix for these two events, jQuery needs a way to detect if a browser allowssubmit and change events to bubble or not. jQuery team does not favor browsersniffing. So how to go about detecting event support without browser sniffing.</p><p>Juriy Zaytsev posted an excellent blog titled<a href="http://perfectionkills.com/detecting-event-support-without-browser-sniffing">Detecting event support without browser sniffing</a>. Here is the short and concise way he proposes to find out if an event issupported by a browser.</p><pre><code class="language-javascript">var isEventSupported = (function () {  var TAGNAMES = {    select: &quot;input&quot;,    change: &quot;input&quot;,    submit: &quot;form&quot;,    reset: &quot;form&quot;,    error: &quot;img&quot;,    load: &quot;img&quot;,    abort: &quot;img&quot;,  };  function isEventSupported(eventName) {    var el = document.createElement(TAGNAMES[eventName] || &quot;div&quot;);    eventName = &quot;on&quot; + eventName;    var isSupported = eventName in el;    if (!isSupported) {      el.setAttribute(eventName, &quot;return;&quot;);      isSupported = typeof el[eventName] == &quot;function&quot;;    }    el = null;    return isSupported;  }  return isEventSupported;})();</code></pre><p>In the comments section John Resig mentioned that this technique can also beused to find out if an event bubbles or not.</p><p>John committed following code to jQuery.</p><pre><code class="language-javascript">var eventSupported = function (eventName) {  var el = document.createElement(&quot;div&quot;);  eventName = &quot;on&quot; + eventName;  var isSupported = eventName in el;  if (!isSupported) {    el.setAttribute(eventName, &quot;return;&quot;);    isSupported = typeof el[eventName] === &quot;function&quot;;  }  el = null;  return isSupported;};jQuery.support.submitBubbles = eventSupported(&quot;submit&quot;);jQuery.support.changeBubbles = eventSupported(&quot;change&quot;);</code></pre><p>Next task is to actually make a change event or a submit event bubble if ,basedon above code, it is determined that browse is not bubbling those events .</p><h2>Making change event bubble</h2><p>On a form a person can change so many things including checkbox, radio button,select menu, textarea etc. jQuery team implemented a full blown change trackerwhich would detect every single change on the form and will act accordingly.</p><p>Radio button, checkbox and select changes will be detected via change event.Here is the code.</p><pre><code class="language-javascript">click: function( e ) {var elem = e.target, type = elem.type;if ( type === &quot;radio&quot; || type === &quot;checkbox&quot; || elem.nodeName.toLowerCase() === &quot;select&quot; ) {return testChange.call( this, e );}},</code></pre><p>In order to detect changes on other fields like input field, textarea etc<code>keydown</code> event would be used. Here it the code.</p><pre><code class="language-javascript">keydown: function( e ) {var elem = e.target, type = elem.type;if ( (e.keyCode === 13 &amp;&amp; elem.nodeName.toLowerCase() !== &quot;textarea&quot;) ||(e.keyCode === 32 &amp;&amp; (type === &quot;checkbox&quot; || type === &quot;radio&quot;)) ||type === &quot;select-multiple&quot; ) {return testChange.call( this, e );}},</code></pre><p>IE has a proprietary event called <code>beforeactivate</code> which gets fired before anychange happens. This event is used to store the existing value of the field.After the click or keydown event the changed value is captured. Then these twovalues are matched to see if really a change has happened. Here is code fordetecting the match.</p><pre><code class="language-javascript">function testChange(e) {  var elem = e.target,    data,    val;  if (!formElems.test(elem.nodeName) || elem.readOnly) {    return;  }  data = jQuery.data(elem, &quot;_change_data&quot;);  val = getVal(elem);  if (val === data) {    return;  }  // the current data will be also retrieved by beforeactivate  if (e.type !== &quot;focusout&quot; || elem.type !== &quot;radio&quot;) {    jQuery.data(elem, &quot;_change_data&quot;, val);  }  if (elem.type !== &quot;select&quot; &amp;&amp; (data != null || val)) {    e.type = &quot;change&quot;;    return jQuery.event.trigger(e, arguments[1], this);  }}</code></pre><p>Here is<a href="http://github.com/jquery/jquery/commit/d42afd0f657d12d6daba6894d40226bea83fe1b6">the commit</a>that fixed this issue.</p><pre><code class="language-javascript">jQuery.event.special.change = {filters: {focusout: testChange,click: function( e ) {var elem = e.target, type = elem.type;if ( type === &quot;radio&quot; || type === &quot;checkbox&quot; || elem.nodeName.toLowerCase() === &quot;select&quot; ) {return testChange.call( this, e );}},// Change has to be called before submit// Keydown will be called before keypress, which is used in submit-event delegationkeydown: function( e ) {var elem = e.target, type = elem.type;if ( (e.keyCode === 13 &amp;&amp; elem.nodeName.toLowerCase() !== &quot;textarea&quot;) ||(e.keyCode === 32 &amp;&amp; (type === &quot;checkbox&quot; || type === &quot;radio&quot;)) ||type === &quot;select-multiple&quot; ) {return testChange.call( this, e );}},// Beforeactivate happens also before the previous element is blurred// with this event you can't trigger a change event, but you can store// information/focus[in] is not needed anymorebeforeactivate: function( e ) {var elem = e.target;if ( elem.nodeName.toLowerCase() === &quot;input&quot; &amp;&amp; elem.type === &quot;radio&quot; ) {jQuery.data( elem, &quot;_change_data&quot;, getVal(elem) );}}},setup: function( data, namespaces, fn ) {for ( var type in changeFilters ) {jQuery.event.add( this, type + &quot;.specialChange.&quot; + fn.guid, changeFilters[type] );}return formElems.test( this.nodeName );},remove: function( namespaces, fn ) {for ( var type in changeFilters ) {jQuery.event.remove( this, type + &quot;.specialChange&quot; + (fn ? &quot;.&quot;+fn.guid : &quot;&quot;), changeFilters[type] );}return formElems.test( this.nodeName );}};var changeFilters = jQuery.event.special.change.filters;}</code></pre><h2>Making submit event bubble</h2><p>In order to detect submission of a form, one needs to watch for click event on asubmit button or an image button. Additionally one can hit 'enter' usingkeyboard and can submit the form. All of these need be tracked.</p><pre><code class="language-javascript">jQuery.event.special.submit = {  setup: function (data, namespaces, fn) {    if (this.nodeName.toLowerCase() !== &quot;form&quot;) {      jQuery.event.add(this, &quot;click.specialSubmit.&quot; + fn.guid, function (e) {        var elem = e.target,          type = elem.type;        if (          (type === &quot;submit&quot; || type === &quot;image&quot;) &amp;&amp;          jQuery(elem).closest(&quot;form&quot;).length        ) {          return trigger(&quot;submit&quot;, this, arguments);        }      });      jQuery.event.add(this, &quot;keypress.specialSubmit.&quot; + fn.guid, function (e) {        var elem = e.target,          type = elem.type;        if (          (type === &quot;text&quot; || type === &quot;password&quot;) &amp;&amp;          jQuery(elem).closest(&quot;form&quot;).length &amp;&amp;          e.keyCode === 13        ) {          return trigger(&quot;submit&quot;, this, arguments);        }      });    }  },  remove: function (namespaces, fn) {    jQuery.event.remove(      this,      &quot;click.specialSubmit&quot; + (fn ? &quot;.&quot; + fn.guid : &quot;&quot;)    );    jQuery.event.remove(      this,      &quot;keypress.specialSubmit&quot; + (fn ? &quot;.&quot; + fn.guid : &quot;&quot;)    );  },};</code></pre><p>As you can see if a submit button or an image is clicked inside a form thesubmit event is triggered. Additionally keypress event is monitored and if the<a href="http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx">keyCode</a>is 13 then the form is submitted.</p><p>live method is just pure awesome. It is great to see last few wrinkles gettingsorted out. A big <code>Thank You</code> to Justin Meyer of<a href="http://javascriptmvc.com">JavaScriptMVC</a> who submitted most of the patch forfixing this vexing issue.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Calling a method on a jQuery collection]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection"/>
      <updated>2010-01-12T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection</id>
      <content type="html"><![CDATA[<p>I was going through the<a href="http://jqueryfordesigners.com/adding-keyboard-navigation">Adding keyboard navigation</a>and noticed that Remi replaced this code</p><pre><code class="language-javascript">$(&quot;.coda-slider-wrapper ul a.current&quot;).parent().next().find(&quot;a&quot;).click();</code></pre><p>with this code</p><pre><code class="language-javascript">var direction = &quot;next&quot;;$(&quot;.coda-slider-wrapper ul a.current&quot;).parent()[direction]().find(&quot;a&quot;).click();</code></pre><p>I had never seen anything like that. In the above mentioned article, Remi used<code>next</code> and <code>prev</code> methods. However I wanted to know all the options I could passsince this feature is not very documented.</p><h2>Snippet from jQuery source code</h2><p>Here is code from jQuery that makes that above method work.</p><pre><code class="language-javascript">jQuery.each(  {    parent: function (elem) {      return elem.parentNode;    },    parents: function (elem) {      return jQuery.dir(elem, &quot;parentNode&quot;);    },    next: function (elem) {      return jQuery.nth(elem, 2, &quot;nextSibling&quot;);    },    prev: function (elem) {      return jQuery.nth(elem, 2, &quot;previousSibling&quot;);    },    nextAll: function (elem) {      return jQuery.dir(elem, &quot;nextSibling&quot;);    },    prevAll: function (elem) {      return jQuery.dir(elem, &quot;previousSibling&quot;);    },    siblings: function (elem) {      return jQuery.sibling(elem.parentNode.firstChild, elem);    },    children: function (elem) {      return jQuery.sibling(elem.firstChild);    },    contents: function (elem) {      return jQuery.nodeName(elem, &quot;iframe&quot;)        ? elem.contentDocument || elem.contentWindow.document        : jQuery.makeArray(elem.childNodes);    },  },  function (name, fn) {    jQuery.fn[name] = function (selector) {      var ret = jQuery.map(this, fn);      if (selector &amp;&amp; typeof selector == &quot;string&quot;)        ret = jQuery.multiFilter(selector, ret);      return this.pushStack(jQuery.unique(ret), name, selector);    };  });</code></pre><p>As you can see, a variety of selectors can be passed to jQueryCollection[].</p><p>If you want to give a try, any jQuery enabled site should perform all of thebelow mentioned code without any problem.</p><pre><code class="language-javascript">var a = $(&quot;a:first&quot;);var log = console.log;log(a[&quot;parent&quot;]());log(a[&quot;parents&quot;]());log(a[&quot;next&quot;]());log(a[&quot;prev&quot;]());log(a[&quot;nextAll&quot;]());log(a[&quot;prevAll&quot;]());log(a[&quot;siblings&quot;]());log(a[&quot;children&quot;]());log(a[&quot;contents&quot;]());</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Use end more often in jQuery while building DOM elements]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements"/>
      <updated>2009-11-11T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements</id>
      <content type="html"><![CDATA[<p>I want to create following markup dynamically using jQuery.</p><pre><code class="language-html">&lt;div&gt;  &lt;p&gt;This is p&lt;/p&gt;&lt;/div&gt;</code></pre><p>Following jQuery code will do the work.</p><pre><code class="language-javascript">$(document).ready(function () {  var div = $(&quot;&lt;div&gt;&lt;/div&gt;&quot;);  var p = $(&quot;&lt;p&gt;&lt;/p&gt;&quot;).text(&quot;this is p&quot;).appendTo(div);  $(&quot;body&quot;).append(div);});</code></pre><p>A better way to accomplish the same is presented below.</p><pre><code class="language-javascript">$(&quot;&lt;div&gt;&lt;/div&gt;&quot;)  .append(&quot;&lt;p&gt;&lt;/p&gt;&quot;)  .find(&quot;p&quot;)  .text(&quot;this is p&quot;)  .end()  .appendTo(&quot;body&quot;);</code></pre><p>Using <code>.end()</code> you can go back one level. And you can use <code>.end()</code> any number oftimes to get out of a deeply nested tag.</p><pre><code class="language-javascript">$(&quot;&lt;div&gt;&lt;/div&gt;&quot;)  .append(&quot;&lt;p&gt;&lt;/p&gt;&quot;)  .find(&quot;p&quot;)  .append(&quot;&lt;span&gt;&lt;/span&gt;&quot;)  .find(&quot;span&quot;)  .text(&quot;this is span&quot;)  .end()  .end()  .appendTo(&quot;body&quot;);</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[livequery in jQuery]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery"/>
      <updated>2009-10-14T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery</id>
      <content type="html"><![CDATA[<p><em>Following code has been tested with jQuery 1.3.2 version .</em></p><p>All the JavaScript code mentioned in this blog should be tried on firebug.</p><p>The super popular <a href="http://docs.jquery.com/Events/live">live method</a> was added tojQuery 1.3 . It works just great. Except when it does not work. As per thedocumentation this method does not work in following cases: blur, focus,mouseenter, mouseleave, change, submit .</p><h2>How binding events work in jQuery</h2><pre><code class="language-javascript">$(&quot;a&quot;).click(function () {  console.log(&quot;clicked&quot;);});</code></pre><p>In above case <code>click</code> event is bound to all the links in the <code>document</code>. jQuerystores such binding information as <code>data</code> attribute of the bound element. Thisis how I can access the list of all functions bound to an element.</p><pre><code class="language-javascript">$(&quot;a&quot;).data(&quot;events&quot;); // Object click=Object</code></pre><p>If a new link is dynamically added then that new link will not get this clickbehavior. To solve this problem I can use live method.</p><h2>Trying out live event</h2><pre><code class="language-javascript">$(&quot;a&quot;).live(&quot;click&quot;, function () {  console.log(&quot;clicked&quot;);});</code></pre><p>If I add a new <code>a</code> tag dynamically then that tag will automatically get the newclick behavior. That's great.</p><p>Just like the previous section, now I am going to find the events bound to <code>a</code>element. However when I execute following code I get <code>undefined</code> .</p><pre><code class="language-javascript">$('a').data('events')); //undefined</code></pre><p>Why is that. In the previous section I showed that all the events bound to anelement are stored as the data attribute of that element. Well, live isdifferent. live events are not bound to the element directly. They are bound tothe top level 'document'. I can verify this by trying out this code</p><pre><code class="language-javascript">jQuery.data(document, &quot;events&quot;).live; //Object</code></pre><h2>How does live method work</h2><p>live methods do not set anything on elements directly. All the event handlersare set at the document level. It means that in order for live methods to work,event bubbling is required. If you don't know what event bubbling is then<a href="http://www.quirksmode.org/js/events_order.html">read her</a> . It also means thatevent should not be stopped while it is propagating to document. If eventpropagation is stopped then event handlers bound at the document level willnever know about that event and live method will fail.</p><p>The strategy to let someone else deal with the event is called<code>event delegation</code>.</p><p>When live method is called then a binding is done at the document level. Looselytranslated this is what is basically happening.</p><pre><code class="language-javascript">$(document).bind(&quot;click&quot;, function (event) {  var $target = $(event.target);  if ($target.is(&quot;p&quot;)) {    console.log(&quot;p was clicked&quot;);  }});</code></pre><p>As you can see when a click on <code>p</code> event bubbles all the way to the top thenthat event is captured by document and necessary action is taken if the targetelement matches.</p><p>It is clear that if the click event is stopped before it reaches document thenlive method will not work. I will show you an example.</p><pre><code class="language-html">&lt;div id=&quot;parent&quot;&gt;  Languages  &lt;p&gt;Java&lt;/p&gt;  &lt;p&gt;Javascript&lt;/p&gt;&lt;/div&gt;</code></pre><pre><code class="language-javascript">$(&quot;p&quot;).live(&quot;click&quot;, function (e) {  console.log(&quot;p was clicked&quot;);});</code></pre><p>If I click on <code>Java</code> or <code>Javascript</code> I get a message on console. live is workinggreat. Now I'll stop the event propagation when event reaches to div.</p><pre><code class="language-javascript">$(&quot;p&quot;).live(&quot;click&quot;, function (e) {  console.log(&quot;p was clicked&quot;);});$(&quot;#parent&quot;).click(function (e) {  console.log(&quot;stopping propagation&quot;);  e.stopPropagation();});</code></pre><p>Now you will notice that live is no more working.</p><h2>live does not work when event bubbling is not supported</h2><p>In the previous section I showed that when event does not bubble up to documentthen live fails. It means that all the events that do not bubble will not work.Which means that events like blur, focus, mouseenter, mouseleave, change andsubmit which do bubble in IE will not work in IE. However note that these eventswill continue to work in Firefox.</p><pre><code class="language-html">&lt;select id=&quot;lab1a&quot; name=&quot;sweets&quot; multiple=&quot;multiple&quot;&gt;  &lt;option&gt;Chocolate&lt;/option&gt;  &lt;option selected=&quot;selected&quot;&gt;Candy&lt;/option&gt;  &lt;option&gt;Taffy&lt;/option&gt;  &lt;option selected=&quot;selected&quot;&gt;Caramel&lt;/option&gt;  &lt;option&gt;Fudge&lt;/option&gt;  &lt;option&gt;Cookie&lt;/option&gt;&lt;/select&gt;&lt;div id=&quot;lab1b&quot; style=&quot;color:red;&quot;&gt;&lt;/div&gt;</code></pre><pre><code class="language-javascript">$(&quot;#lab1a&quot;).live(&quot;change&quot;, function () {  var str = &quot;&quot;;  $(&quot;select option:selected&quot;).each(function () {    str += $(this).text() + &quot; &quot;;  });  $(&quot;#lab1b&quot;).text(str);});</code></pre><p>Above code will work in firefox but it will not work in IE.</p><p>Here is an example of an event that does not work in IE: onchange event.</p><p>DOM models suggest that<a href="http://msdn.microsoft.com/en-us/library/ms536912%28VS.85%29.aspx">onchange event should bubble</a>. However msdn documentation clearly says that<a href="http://msdn.microsoft.com/en-us/library/ms536912%28VS.85%29.aspx">onchange event does not bubble</a>.</p><h2>Make all the live method problems go away</h2><p>To recap live method will not work in following cases:</p><ul><li>live method works on event propagation, if an event is stopped while it isbubbling then live will not work.</li><li>IE does not support bubbling for certain events. live method on those eventswill not work in IE.</li></ul><p>There is a way to get around to both the problems.</p><p><a href="http://brandonaaron.net/code">Brandon Aaron</a> developed<a href="http://docs.jquery.com/Plugins/livequery">livequery plugin</a> which was finallymerged into jQuery as live method. livequery plugin solves both the problemslisted above and the code works in IE too.</p><p>First step is to include this plugin</p><pre><code class="language-html">&lt;script  src=&quot;http://github.com/brandonaaron/livequery/raw/master/jquery.livequery.js&quot;  type=&quot;text/javascript&quot;&gt;&lt;/script&gt;</code></pre><p>Now try this code.</p><pre><code class="language-javascript">$(&quot;p&quot;).livequery(&quot;click&quot;, function (e) {  alert(&quot;p was clicked&quot;);});$(&quot;#parent&quot;).click(function (e) {  alert(&quot;stopping progpagation&quot;);  e.stopPropagation();});$(&quot;#lab1a&quot;).livequery(&quot;change&quot;, function () {  var str = &quot;&quot;;  $(&quot;select option:selected&quot;).each(function () {    str += $(this).text() + &quot; &quot;;  });  $(&quot;#lab1b&quot;).text(str);});</code></pre><pre><code class="language-html">&lt;select id=&quot;lab1a&quot; name=&quot;sweets&quot; multiple=&quot;multiple&quot;&gt;  &lt;option&gt;Chocolate&lt;/option&gt;  &lt;option selected=&quot;selected&quot;&gt;Candy&lt;/option&gt;  &lt;option&gt;Taffy&lt;/option&gt;  &lt;option selected=&quot;selected&quot;&gt;Caramel&lt;/option&gt;  &lt;option&gt;Fudge&lt;/option&gt;  &lt;option&gt;Cookie&lt;/option&gt;&lt;/select&gt;&lt;div id=&quot;lab1b&quot; style=&quot;color:red;&quot;&gt;&lt;/div&gt;&lt;div id=&quot;parent&quot;&gt;  Languages  &lt;p&gt;Java&lt;/p&gt;  &lt;p&gt;Javascript&lt;/p&gt;&lt;/div&gt;</code></pre><p>If I click on 'Java' or 'Javascript' I will get proper response even thoughevent propagation is being stopped. Also even though change event does notbubble in IE, above code works in IE.</p><p>livequery works because livequery ,unlike live, method does not do binding atthe document level. livequery does binding at the element level. You can findthat out by running following code.</p><pre><code class="language-javascript">$(&quot;p&quot;).data(&quot;events&quot;);</code></pre><p>Above code will produce result if I am using livequery. Above code will notproduce any result if I am using live method.</p><p>The key piece of code in the plugin that makes all this work is</p><pre><code class="language-javascript">// Create a timeout to check the queue and actually run the Live Queries$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);</code></pre><p>Every 20 milliseconds livequery runs all the bindings defined in livequery andthen binds the matched element with the event.</p><p>By understanding the internals of how live and livequery are implemented, nowyou can choose to use livequery in certain cases where live will not work. Alsoit helps to understand how live actually works.</p><h2>Live method finds elements and then throws it away. Not very efficient.</h2><p>A typical use of live method is something like this.</p><pre><code class="language-javascript">$(&quot;p&quot;).live(&quot;click&quot;, function (e) {  console.log(&quot;p was clicked&quot;);});</code></pre><p>As it has already been discussed a live method registers events at documentlevel.</p><p>However when <code>$('p').live(...)</code> is evaluated then jQuery first goes and findsall the <code>p</code> elements. And then what does it do with those elements. Nothing.That's right. jQuery throws away all those <code>p</code> elements which were just foundwithout using them. What a waste.</p><p>If your application has a lot of live methods and this might slow down theperformance of the application.</p><p>A better solution would have been to design an API like this one:</p><pre><code class="language-javascript">$.live('p', 'click', function(){..});~~~jQuery is flexible and I can create my own live method but it will add to the confusion. Another solution would be to make the call to live method without first finding all those `p` element. Here is how it can be done.~~~javascriptvar myDocument = $(document);myDocument.selector = 'p';myDocument.live('click', function(){  console.log('p was clicked');});</code></pre><p>In the above case no element will be selected only to be thrown away. This ismuch better.</p><h2>Seeing is believing</h2><p>In the previous section, I showed how live method can be made to work withoutfirst selecting the elements. However a friend of mine asked me if I couldconclusively prove that in the real live method a find is <em>actually</em> done. Andin my solution a find call is <em>not</em> done.</p><p>Here I am showing you the overriding <em>find</em> method. In this method I amoverriding the original find method. I will put a log message before passing thefind method to the original method.</p><pre><code class="language-javascript">(function () {  var originalFindMethod = jQuery.fn.find;  jQuery.fn.find = function () {    console.log(&quot;find was called&quot;);    originalFindMethod.apply(this, arguments);  };})();$(document).ready(function () {  $(&quot;p&quot;).live(&quot;click&quot;, function () {    console.log(&quot;p was clicked&quot;);  });});</code></pre><p>In the above case you will get message on firebug console confirming that findis indeed invoked when live method is called.</p><p>Here is revised version of live. Try this one.</p><pre><code class="language-javascript">(function () {  var originalFindMethod = jQuery.fn.find;  jQuery.fn.find = function () {    console.log(&quot;find was called&quot;);    originalFindMethod.apply(this, arguments);  };})();$(document).ready(function () {  var myDocument = $(document);  myDocument.selector = &quot;p&quot;;  myDocument.live(&quot;click&quot;, function () {    console.log(&quot;p was clicked&quot;);  });});</code></pre><p>Above version does not print 'find was called'.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Wrapping functions with self invoking jQuery]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace"/>
      <updated>2009-09-03T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace</id>
      <content type="html"><![CDATA[<p><em>Following code is tested with jQuery 1.3 .</em></p><p>I have following code which depends on jQuery.</p><pre><code class="language-javascript">var Search = {  initAction: function ($elm) {    if ($elm.attr(&quot;value&quot;).length === 0) {      $elm.attr(&quot;value&quot;, &quot;search&quot;);    }  },  blurAction: function ($elm) {    if ($elm.attr(&quot;value&quot;) === &quot;search&quot;) {      $elm.attr(&quot;value&quot;, &quot;&quot;);    }  },};Search.initAction($(&quot;#query_term_input&quot;));Search.blurAction($(&quot;#query_term_input&quot;));</code></pre><p>Everything is cool.</p><p>Next, company decides to use a cool JavaScript widget that depends on Prototypelibrary. After adding the Prototype library my code starts failing. I have beenasked to fix my code.</p><p>I can obviously go through the code and do a mass find <code>$</code> and replace $ with<code>jQuery</code>. This is error prone.</p><p>A better solution would be to make use of<a href="understanding-jquery-plugin-pattern-and-self-invoking-javascript-function">self invoking function</a>and redefine <code>$</code> to <code>jQuery</code> .</p><pre><code class="language-javascript">var Search = (function ($) {  return {    initAction: function ($elm) {      if ($elm.attr(&quot;value&quot;).length === 0) {        $elm.attr(&quot;value&quot;, &quot;search&quot;);      }    },    blurAction: function ($elm) {      if ($elm.attr(&quot;value&quot;) === &quot;search&quot;) {        $elm.attr(&quot;value&quot;, &quot;&quot;);      }    },  }; // return})(jQuery);Search.initAction(jQuery(&quot;#query_term_input&quot;));Search.blurAction(jQuery(&quot;#query_term_input&quot;));</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[Understanding this in Javascript object literal]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/understanding-this-in-javascript-object-literal"/>
      <updated>2009-08-06T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/understanding-this-in-javascript-object-literal</id>
      <content type="html"><![CDATA[<p>Here is code.</p><pre><code class="language-javascript">var foo = {  first: function () {    console.log(&quot;I am first&quot;);  },  second: function () {    console.log(&quot;I am second&quot;);  },};foo.first();foo.second();</code></pre><p>Everything works fine.</p><p>Now there is a need for function <code>second</code> to call function <code>first</code>. Try this andit will fail.</p><pre><code class="language-javascript">var foo = {  first: function () {    console.log(&quot;I am first&quot;);  },  second: function () {    console.log(&quot;I am second&quot;);    first();  },};foo.second();</code></pre><p>One way to fix this problem is to hardcode value <code>foo</code> inside the <code>second</code>function. Following code works.</p><pre><code class="language-javascript">var foo = {  first: function () {    console.log(&quot;I am first&quot;);  },  second: function () {    console.log(&quot;I am second&quot;);    foo.first();  },};foo.second();</code></pre><p>Above code works but hardcoding the value of <code>foo</code> inside the object literal isnot good. A better way would be to replace the hardcoded name with <code>this</code> .</p><pre><code class="language-javascript">var foo = {  first: function () {    console.log(&quot;I am first&quot;);  },  second: function () {    console.log(&quot;I am second&quot;);    this.first();  },};foo.second();</code></pre><p>All is good.</p><h2>Chasing this</h2><p>Javascript allows one to create function inside a function. Now I am changingthe implementation of method <code>second</code>. Now this method would return anotherfunction.</p><pre><code class="language-javascript">var foo = {  first: function () {    console.log(&quot;I am first&quot;);  },  second: function () {    return function () {      this.first();    };  },};foo.second()();</code></pre><p>Also note that in order to invoke the returned function I have double <code>()()</code> atthe end.</p><p>Above code does not work. It did not work because <code>this</code> has changed. Now <code>this</code>in <code>second</code> function refers to the global object rather than referring to the<code>foo</code> object.</p><p>Fix is simple. In the function <code>second</code> store the value of <code>this</code> in a temporaryvariable and the inner function should use that temporary variable. Thissolution will work because of Javascript's inherent support for closure.</p><pre><code class="language-javascript">var foo = {  first: function () {    console.log(&quot;I am first&quot;);  },  second: function () {    var self = this;    return function () {      self.first();    };  },};foo.second()();</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[jQuery custom events]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-custom-events"/>
      <updated>2009-07-31T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-custom-events</id>
      <content type="html"><![CDATA[<p><em>Following code has been tested with jQuery 1.3 .</em></p><p>Javascript is all about interactions. When an event happens then somethingshould happen. For example hover, click, focus, mouseover etc are basic eventswhich are used on a regular basis. jQuery provides a method called<a href="http://docs.jquery.com/Events/bind#typedatafn">bind</a> to bind an action to anevent. For example, if we want an alert message when we click on a link thenthat can be done like this.</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;click&quot;, function () {  alert(&quot;I have been clicked&quot;);});</code></pre><p>jQuery also allows developers to make use of custom events. How it is going tohelp us, we are going to see it shortly. First let's take a look at a basiccalendar application.</p><p>This is a simple javascript calendar which primarily does four things: rendercalendar itself, pull data from API and update calendar with API data, abilityto collapse event information and ability to expand event information.</p><p>Code looks like this.</p><pre><code class="language-javascript">function redrawForMonth(d) {  //business logic to render calendar  $(&quot;#monthly_calendar_umbrella&quot;).updateCalendarWithAPIData();  $(&quot;#monthly_calendar_umbrella&quot;).ExpandAllEvents();}function updateCalendarWithAPIData() {  //business logic to get the data from API and appending data to appropriate date cell}function CollapseAllEvents() {  //business logic}function ExpandAllEvents() {  //business logic}</code></pre><p>In the above case we have four methods. If all the implementation is filled outand helper methods are added then ,in total, we'll have tons of methods.</p><p>And slowly, it'll become difficult to see which methods act on the main element<code>monthly_calendar_umbrella</code>.</p><p>Let's look at the same functionality if implemented using jQuery custom events.</p><pre><code class="language-javascript">$(&quot;#monthly_calendar_umbrella&quot;)  .bind(&quot;redrawForMonth&quot;, function (e, d) {})  .bind(&quot;updateCalendarWithAPIData&quot;, function (e, d) {})  .bind(&quot;CollapseAllEvents&quot;, function (e) {})  .bind(&quot;ExpandAllEvents&quot;, function (e) {});</code></pre><p>First difference, you will notice is how nicely all the actions possible on themain element are laid out. In this case just one look at the code tells me thatfour actions can be performed on the main element. This was not so obvious fromthe first version of the code.</p><p>In this case, I am binding events such as 'redrawFroMonth' to the element.Obviously 'redrawForMonth' is not a native event such as 'click' or 'submit'.This is what I mean by binding 'custom events' to elements. In this case'redrawForMonth' is a custom event.</p><p>The other thing that is not so obvious is the shift in focus. Traditionaljavascript programming has been too obsessed with the elements that is clickedor submitted that causes an action. The emphasis has been too much on keepingthe code around the element that creates an action. In this case the code hasbeen developed around the element that is being acted upon.</p><p>Now, the last part of the discussion is how to trigger custom events. Well,jQuery has a method called<a href="http://docs.jquery.com/Events/trigger#eventdata">trigger</a> .</p><p>Note that while binding a function is passed. The first parameter of thatfunction is always an event handler. In the below example I am passing only oneparameter even though the function takes two parameters: event handler elementand the parameter I defined.</p><pre><code class="language-javascript">$(&quot;#monthly_calendar_umbrella&quot;).trigger(&quot;redrawForMonth&quot;, new Date());</code></pre>]]></content>
    </entry><entry>
       <title><![CDATA[jQuery base code to create a jQuery plugin]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-base-code-to-create-a-jquery-plugin"/>
      <updated>2009-07-24T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-base-code-to-create-a-jquery-plugin</id>
      <content type="html"><![CDATA[<p><em>Following code has been tested with jQuery 1.3 .</em></p><p>Recently I was discussing how to create a jQuery plugin with a friend of mine.In the end I had a base code that should work as a starting point of any jQueryplugin.</p><p><a href="http://gist.github.com/154375">Take a look</a> here .</p>]]></content>
    </entry><entry>
       <title><![CDATA[Inspecting jQuery internals and storing information]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/jquery-data-for-inspecting-jquery-internals-and-for-storing-information"/>
      <updated>2009-07-23T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/jquery-data-for-inspecting-jquery-internals-and-for-storing-information</id>
      <content type="html"><![CDATA[<p>Following code has been tested with jQuery 1.3 .</p><p>Let's say that I have bound all the links to display an alert.</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;click&quot;, function (e) {  e.preventDefault();  alert(&quot;clicked&quot;);});</code></pre><p>Mine is a large application and a co-worker has added another javascript filewhich does this</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;click&quot;, function (e) {  e.preventDefault();  alert(&quot;hello&quot;);});</code></pre><p>Now if I click on a link I get two alerts. Not good. One way to debug would beto go through all the included javascript files.</p><p>However it would be cool if there is a way to find all the click handlersassociated with an element.</p><p>jQuery has <a href="http://docs.jquery.com/Internals/jQuery.data">data method</a> which ituses internally to store information. jQuery uses data method to store all thehandlers associated with an element. We could use this information to ouradvantage. Here I am trying to find out all the click handlers associated withthe first link.</p><pre><code class="language-javascript">var output = jQuery.data($(&quot;a&quot;).get(0), &quot;events&quot;);jQuery.each(output.click, function (key, value) {  alert(value);});</code></pre><p>The output looks like this</p><pre><code class="language-javascript">function (e) { e.preventDefault(); alert(&quot;clicked&quot;); }function (e) { e.preventDefault(); alert(&quot;hello&quot;); }</code></pre><p>jQuery.data method is also very useful if you want to store some informationabout an element. For example, in an application you need to store informationabout people. In the html page you are only displaying names. And when a name isclicked then you want to display age, hometown and the company they work for.You can store information about each user using jQuery.data and you can retrieveit when username is clicked.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Event propagation and peventDefault]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/event-propagation-and-peventdefault"/>
      <updated>2009-07-20T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/event-propagation-and-peventdefault</id>
      <content type="html"><![CDATA[<p>Let's look at sample html.</p><pre><code class="language-html">&lt;div id=&quot;parent&quot;&gt;  Languages  &lt;p&gt;Java&lt;/p&gt;  &lt;p&gt;Javascript&lt;/p&gt;&lt;/div&gt;</code></pre><p>And here is the javascript code. Run the code with jQuery-1.3.2 .</p><pre><code class="language-javascript">$(document).ready(function () {  $(&quot;#parent&quot;).click(function () {    alert(&quot;parent was clicked&quot;);  });  $(&quot;#parent p&quot;).click(function () {    alert(&quot;p was clicked&quot;);  });});</code></pre><p>When you click on <code>Java</code> then you will get two alerts. That is because the clickon element p will propagate outward and it will be caught by element div whichhas onclick trigger.</p><p>If you do not want the event to propagate then here is a way to stop it.</p><pre><code class="language-javascript">$(document).ready(function () {  $(&quot;#parent&quot;).click(function () {    alert(&quot;parent was clicked&quot;);  });  $(&quot;#parent p&quot;).click(function (e) {    alert(&quot;p was clicked&quot;);    e.stopPropagation();  });});</code></pre><h2>Stopping the default behavior</h2><p>Converting a regular html link into an AJAX request is easy. One of the thingsyou need to do is to <code>return false</code> so that the click operation does not performits default behavior.</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;click&quot;, function () {  alert(&quot;clicked&quot;);  return false;});</code></pre><p>However there is another way to handle such cases. <code>preventDefault</code> stops thedefault behavior. The same code could be written as</p><pre><code class="language-javascript">$(&quot;a&quot;).bind(&quot;click&quot;, function (e) {  e.preventDefault();  alert(&quot;clicked&quot;);});</code></pre><p><em>Not sure why but I have noticed that e.preventDefault() should be the firstline in the function. If I switch the order of e.preventDefault and alertmessage in the above javascript then it does not work in Firefox/mac</em>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[Functional scope in Javascript]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me"/>
      <updated>2009-06-30T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me</id>
      <content type="html"><![CDATA[<p>Javascript continues to surprise me. Check out this code.</p><pre><code class="language-javascript">function foo() {  var x = 100;  alert(x);  for (var x = 1; x &lt;= 10; x++) {}  alert(x);}foo();</code></pre><p>What do you think the value of second alert will be. I thought it would be 100but the answer is 11. That's because the scope of a local variable in Javascriptis not limited to the loop. Rather the scope of a local variable is felt allover the function.</p><p>Before you look at the next piece of code remember that defining a variablewithout the <code>var</code> prefix makes that variable a global variable.</p><pre><code class="language-javascript">fav_star = &quot;Angelina&quot;; /* it is a global variable */function foo() {  var message = &quot;fav star is &quot; + fav_star;  alert(message);  var fav_star = &quot;Jennifer&quot;;  var message2 = &quot;fav star is &quot; + fav_star;  alert(message2);}foo();</code></pre><p>What do you think would be the alert value first time? I thought it would be<code>Angelina</code> but the correct answer is <code>undefined</code>. That is because it does notmatter where the variable is defined. As long as the variable is definedanywhere within a function then that variable will be set to <code>undefined</code>. It iswhen the statement is executed then the value of the variable changes from<code>undefined</code> to <code>Jennifer</code>.</p><p>Thanks to my friend Subba Rao for bringing this feature of Javascript to myattention and for discussing it.</p>]]></content>
    </entry><entry>
       <title><![CDATA[JS tip - Avoiding polluting the global namespace]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/javascript-tip-do-not-pollute-global-namespace-with-utility-functions"/>
      <updated>2009-03-18T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/javascript-tip-do-not-pollute-global-namespace-with-utility-functions</id>
      <content type="html"><![CDATA[<p>I am learning Javascript and as I do more Javascript work I am learning not onlythe language but also the best practices. Today I am developing a Javascriptcalendar. In the process of creating the calendar I created a bunch of utilityfunctions that are available at global namespace.</p><h2>What are we talking about</h2><p>My main concern is that as Javascript developer I should not be polluting globalnamespace. I could write the calendar code like this.</p><pre><code class="language-javascript">showCalendar = function (options, d) {};calendarHeaderMonth = function (opts) {};calendarHeaderWeek = function (opts) {};calendarData = function (opts) {};drawCalendar = function (opts, d) {};getCellID = function (year, month, day) {};// use showCalendarshowCalendar({}, new Date());</code></pre><p>You can see that the main method that I want to expose to global namespace is<code>showCalendar</code>. However I am also exposing six other functions to globalnamespace. It means that if some user has declared a global namespace functionnamed <code>getCellID</code> then my <code>getCellID</code> is going to collide with the user'sfunction. This is not good.</p><h2>Goal</h2><p>The goal is to refactor the code in such a way that only one method<code>showCalendar</code> is exposed to the global namespace. In order to test the code atthe very end of the javascript I will invoke a call to method <code>getCellID</code>.</p><pre><code class="language-javascript">showCalendar = function (options, d) {};calendarHeaderMonth = function (opts) {};calendarHeaderWeek = function (opts) {};calendarData = function (opts) {};drawCalendar = function (opts, d) {};getCellID = function (year, month, day) {};// use showCalendarshowCalendar({}, new Date());// this call should fail but is not failing nowgetCellID(2009, 5, 4);</code></pre><p>The above call to <code>getCellID</code> is currently being executed successfully. It meansI have polluted the global namespace. I am going to fix it.</p><h2>Solution</h2><p>The solution is to put all the code inside a function. In a function all thevariables and functions declared are scoped only to that function. Out of thatfunction, inner functions cannot be used. Inside this function only one method<code>showCalendar</code> would be exposed.</p><p>Here is the solution.</p><pre><code class="language-javascript">(function () {  // by not declaring var this variable is going to be at global namespace  showCalendar = function (options, d) {};  var calendarHeaderMonth = function (opts) {};  var calendarHeaderWeek = function (opts) {};  var calendarData = function (opts) {};  var drawCalendar = function (opts, d) {};  var getCellID = function (year, month, day) {};})();showCalendar({}, new Date());// this call will failgetCellID(2009, 5, 4);</code></pre><p>In the above case the call to <code>showCalendar</code> was successful. However call to<code>getCallID</code> failed. That's good. It means I am not polluting the globalnamespace.</p><p>If you notice carefully in the above case after declaring an anonymous functionI am invoking that function by having <code>()</code> at the end. You can read more about<a href="understanding-jquery-plugin-pattern-and-self-invoking-javascript-function">self-invoking function here</a>.</p>]]></content>
    </entry><entry>
       <title><![CDATA[jQuery Plugin Pattern & self-invoking javascript function]]></title>
       <author><name>Neeraj Singh</name></author>
      <link href="https://www.bigbinary.com/blog/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function"/>
      <updated>2009-03-13T12:00:00+00:00</updated>
      <id>https://www.bigbinary.com/blog/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function</id>
      <content type="html"><![CDATA[<p>I am learning jQuery and one of things I was struggling with is the pluginpattern. In jQuery world it is very common to wrap the major functionality ofthe application inside a plugin.</p><p><a href="https://www.learningjquery.com/2007/10/a-plugin-development-pattern">Here is a great article</a>which describes in detail how to wrap your javascript code inside a jQueryplugin. The article did a great job of explaining the basics however it took mea while to understand the self-invoking functions.</p><h2>Self-invoking functions</h2><p>self-invoking functions are anonymous functions declared on run time and theninvoke it right then and there. Since they are anonymous functions they can't beinvoked twice. However they are a good candidate for initialization work whichis exactly what is happening in the jQuery plugin pattern.</p><h2>Declaring a function</h2><p>A function can be declared in two ways:</p><pre><code class="language-javascript">function hello() {  alert(&quot;Hello&quot;);}var hello = function () {  alert(&quot;Hello&quot;);};</code></pre><p>The end result in the above two javascript statement was same. In the end avariable named hello was created which is a function.</p><p>Please note that in the above case only the functions are declared. They are notinvoked. In order to invoke the function we have to do this</p><pre><code class="language-javascript">var hello = function () {  alert(&quot;Hello&quot;);};hello();</code></pre><p>How do we invoke an anonymous function. We need to call () on the anonymousfunction. But before that we need to wrap the whole command in (). Take a lookat this</p><pre><code class="language-javascript">// originalfunction hello() {  alert(&quot;Hello&quot;);}// step1 wrap everything in () so that we have a context to invoke(function hello() {  alert(&quot;Hello&quot;);})(  // now call () to invoke this function  function hello() {    alert(&quot;Hello&quot;);  })();</code></pre><p>The final result is weird looking code but it works and that is how an anonymousfunction is declared and invoke on run time.</p><p>With this understanding now it becomes easier to see what is happening in thiscode</p><pre><code class="language-javascript">(function ($) {  // ....})(jQuery);</code></pre><p>In the above case an anonymous function is being created. However unlike myanonymous function this anonymous function take a parameter and the name of thisparameter is $. $ is nothing else but jQuery object that is being passed whileinvoking this function.</p>]]></content>
    </entry>
     </feed>