<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" xml:lang="en-US">
  <title>BigBinary Blog: jQuery</title>
  <subtitle>Deep technical writing on Ruby on Rails, performance, scaling, monitoring and engineering.</subtitle>
  <link rel="self" type="application/atom+xml" href="https://www.bigbinary.com/blog/categories/jquery/feed.xml"/>
  <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/categories/jquery"/>
  <id>https://www.bigbinary.com/blog/categories/jquery</id>
  <updated>2012-05-11T00:00:00.000Z</updated>
  <author>
    <name>BigBinary</name>
    <uri>https://www.bigbinary.com/</uri>
  </author>
  <icon>https://www.bigbinary.com/favicon.ico</icon>
  <logo>https://www.bigbinary.com/images/bigbinary_square_big_logo.png</logo>
  <rights>Copyright 2012 Big Binary LLC</rights>
  <generator uri="https://nextjs.org">Next.js</generator>
  <entry>
      <title type="text"><![CDATA[jquery-ujs and jquery trigger]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-ujs-and-jquery-trigger.png"/>
      <id>https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger</id>
      <published>2012-05-11T00:00:00.000Z</published>
      <updated>2012-05-11T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-ujs-and-jquery-trigger.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[This blog discusses how to make AJAX calls using jquery-ujs. Also discusses why event object is needed which is often the cause of error with lot of code.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-ujs-and-jquery-trigger"><![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. Here
is 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 passed
to 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 why
we 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 the
event object is always passed as the first parameter to the event handler. This
is why when you are using jquery-ujs you have to have the first parameter in the
callback function an event object.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[An inline confirmation utility powered by jQuery]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/iconfirm-an-inline-confirmation-jquery-plugin"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/iconfirm-an-inline-confirmation-jquery-plugin.png"/>
      <id>https://www.bigbinary.com/blog/iconfirm-an-inline-confirmation-jquery-plugin</id>
      <published>2010-11-02T00:00:00.000Z</published>
      <updated>2010-11-02T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/iconfirm-an-inline-confirmation-jquery-plugin.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[This blog discusses an inline confirmation utility developed using jQuery.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/iconfirm-an-inline-confirmation-jquery-plugin"><![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 type="text"><![CDATA[Return false has changed in jquery 1.4.3]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/return-false-in-jquery-1.4.3"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/return-false-in-jquery-1.4.3.png"/>
      <id>https://www.bigbinary.com/blog/return-false-in-jquery-1.4.3</id>
      <published>2010-10-25T00:00:00.000Z</published>
      <updated>2010-10-25T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/return-false-in-jquery-1.4.3.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[The behavior of return false has changed in jQuery 1.4.3.  This blog discusses what changed.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/return-false-in-jquery-1.4.3"><![CDATA[<p>jQuery 1.4.3 was recently
<a href="http://blog.jquery.com/2010/10/16/jquery-143-released/">released</a>. If you
upgrade to jQuery 1.4.3 you will notice that the behavior of <code>return false</code> has
changed 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 link
then 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 the
default 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 you
to <code>www.google.com</code>. However by invoking <code>e.preventDefault()</code> browser will not
go ahead with default behavior and I will <strong>not</strong> 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 event
bubbles all the way up to the top. By invoking <code>e.stopPropagation</code> I am asking
browser to not to propagate the event. In other words the event will stop
bubbling.</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 say
that I catch this event at <code>.two</code> and if I call <code>e.stopPropagation()</code> then this
event 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 at
following 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 that
second 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 any
parent 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. And
calling <code>stopImmediatePropagation</code> means stop passing this event to other event
handlers 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 as
executing:</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 have
added here for visual clarity.</p>
<p>Fact that <code>return false</code> was calling <code>e.stopImmeidatePropagation</code> was a bug. Get
that. 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 this
piece 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 <strong>not</strong> 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. To
get 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 would
have to like to have as much backward compatibility in <code>jquery-ujs</code> as much
possible so that the same code base works with jQuery 1.4 through 1.4.3 since
not 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 at
jquery-ujs and I will take a look at all of them one by one. Please do provide
your feedback.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[List of only the elements that contains]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/list-of-only-the-elements"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/list-of-only-the-elements.png"/>
      <id>https://www.bigbinary.com/blog/list-of-only-the-elements</id>
      <published>2010-04-12T00:00:00.000Z</published>
      <updated>2010-04-12T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/list-of-only-the-elements.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[How to effectively search for a string in DOM elements.  This blog discusses jQuery technique.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/list-of-only-the-elements"><![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. jQuery
supports <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 for
given 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 of
elements 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 type="text"><![CDATA[return false considered harmful in live]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/return-false-considered-harmful-in-live-jquery"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/return-false-considered-harmful-in-live-jquery.png"/>
      <id>https://www.bigbinary.com/blog/return-false-considered-harmful-in-live-jquery</id>
      <published>2010-03-10T00:00:00.000Z</published>
      <updated>2010-03-10T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/return-false-considered-harmful-in-live-jquery.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[If you return false in live operation of jQuery a few unexpected things can happen. See this blog for details.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/return-false-considered-harmful-in-live-jquery"><![CDATA[<p>Checkout following jQuery code written with jQuery.1.4.2. What do you think will
happen 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 invokes
the very first message.</p>
<p><code>return false</code> does two things. It stops the default behavior which is go and
fetch the link mentioned in the <code>href</code> of the anchor tags. Also it stops the
event from bubbling up. Since live method relies on event bubbling, it makes
sense 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 type="text"><![CDATA[Simplest jQuery slideshow code explanation]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/simplest-jquery-slideshow-code-explanation.png"/>
      <id>https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation</id>
      <published>2010-02-18T00:00:00.000Z</published>
      <updated>2010-02-18T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/simplest-jquery-slideshow-code-explanation.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Building slideshow using jQuery could take a bit of code.  This is probably the simplest jQuery slideshow code you would see in action.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/simplest-jquery-slideshow-code-explanation"><![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 full
JavaScript code in its entirety is given below. If you understand this code then
you 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 test
page. 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 run
JavaScript the order is changing.</p>
<p>The order of <code>div</code> elements with class <code>lab</code> is changing because if a jQuery
element is already part of document and that element is being added somewhere
else then jQuery will do <code>cut and paste</code> and <em>not</em> <code>copy and paste</code> . Again
elements that already exist in the document get plucked out of document and then
they 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 and
that image is being added to set again. In simpler terms this is what is
happening. Initially the order is like this.</p>
<pre><code class="language-plaintext">Image1
Image2
Image3
</code></pre>
<p>After the code is executed the order becomes this.</p>
<pre><code class="language-plaintext">Image2
Image3
Image1
</code></pre>
<p>After the code is executed again then the order becomes this.</p>
<pre><code class="language-plaintext">Image3
Image1
Image2
</code></pre>
<p>After the code is executed again then the order becomes this.</p>
<pre><code class="language-plaintext">Image1
Image2
Image3
</code></pre>
<p>And this cycle continues forever.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[How jQuery selects elements using Sizzle]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/how-jquery-selects-elements-using-sizzle"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-jquery-selects-elements-using-sizzle.png"/>
      <id>https://www.bigbinary.com/blog/how-jquery-selects-elements-using-sizzle</id>
      <published>2010-02-15T00:00:00.000Z</published>
      <updated>2010-02-15T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-jquery-selects-elements-using-sizzle.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[jQuery uses Sizzle to selects elements. But how exactly it works. How jQuery gets the elements I want. This blog deep dives into jQuer internals to see how jQuery selects the elements based on provided selectors.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/how-jquery-selects-elements-using-sizzle"><![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 with
the result. This is a good thing. jQuery provides extremely simple API for
selecting 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 many
reasons. And one of the important reasons is the performance of Rich Client. As
more and more web pages use more and more jQuery code, understanding of how
jQuery 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. Ideally
speaking all the html documents should be 100% valid xml documents. However if
you miss out on closing a div then browsers forgive you ( unless you have asked
for 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) that
browser has created in memory. A good example of manipulating the tree is
command like the one give below which would hide the header element. However in
order 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 the
criteria provided by a user. There are many JavaScript selector engines in the
market. 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 article
I 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 could
use 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 browsers
were not much help. It was possible to walk up and down the tree however
traversing the tree was tricky because of two reasons: a) DOM spec is not very
intuitive 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 specification
including 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 modern
browser then jQuery code <code>jQuery('#header a')</code> will not even hit Sizzle. That
query 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('#header
a'). This is one of the reasons why some apps perform much slower on IE6/7
compared to IE8 since a native browser function is much faster than elements
retrieval by Sizzle.</p>
<h2>Selection process</h2>
<p>jQuery has a lot of optimization baked in to make things run faster. In this
section I will go through some of the queries and will try to trace the route
jQuery follows.</p>
<h2>$('#header')</h2>
<p>When jQuery sees that the input string is just one word and is looking for an id
then jQuery invokes document.getElementById . Straight and simple. Sizzle is not
invoked.</p>
<h2>$('#header a') on a modern browser</h2>
<p>If the browser supports querySelectorAll then querySelectorAll will satisfy this
request. 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 an
exception (at least on firefox). The browser will throw an exception because the
querySelectorAll method does not support certain selection criteria. In this
case when browser throws an exception, jQuery will pass on the request to
Sizzle. Sizzle not only supports css 3 selector but it goes above and beyond
that.</p>
<h2>$('.header a') on IE6/7</h2>
<p>On IE6/7 <code>querySelectorAll</code> is not available so jQuery will pass on this request
to Sizzle. Let's see a little bit in detail how Sizzle will go about handling
this case.</p>
<p>Sizzle gets the selector string '.header a'. It splits the string into two parts
and 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 go
right 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 find
out what kind of pattern this string matches. In this case Sizzle is dealing
with 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 function
will 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>. In
short 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 representation
dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML )
</code></pre>
<p>dirCheck method returns whether each element of checkSet passed the test. After
that 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 not
matching 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 methods
are actually implemented.</p>
<h2>Performance Implications</h2>
<p>Now that I have little more understanding of how Sizzle works, I can better
optimize 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 all
the elements with the class <code>employment</code> and then Sizzle will try to filter that
list. 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 most
selection 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 less
specific 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 more
specific.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Understanding jQuery effects queue]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/understanding-jquery-effects-queue"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/understanding-jquery-effects-queue.png"/>
      <id>https://www.bigbinary.com/blog/understanding-jquery-effects-queue</id>
      <published>2010-02-02T00:00:00.000Z</published>
      <updated>2010-02-02T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/understanding-jquery-effects-queue.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[This blog discusses how jQuery effects queue works.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/understanding-jquery-effects-queue"><![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 in
jQuery.</p>
<p>animate method uses a queue inside. This is the queue to which all the pending
activities 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 animation
will not start until the first animation is done. While the first animation is
happening the second animation is added to a queue. Name of this default queue
is <code>fx</code>. This is the queue to which jQuery adds all the pending activities while
one activity is in progress. You can inquire an element about how many pending
activities 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 of
pending activities. First time the number of pending activities is 3 and the
second time it is 1.</p>
<p>Method show and hide also accepts duration. If a duration is passed then that
operation is added to the queue. If duration is not passed or if the duration is
zero 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 are
not 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 and
the hide method are executed simultaneously. Hence the end result is that
element is not hidden.</p>
<p>It could be fixed in a number of ways. One way would be to pass a duration to
hide 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 to
animate 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 have
explicitly put the hide method to the queue.</p>
<p>Note that inside a queue method you must explicitly call <code>dequeue</code> for the next
activity 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 never
take place.</p>
<p>Also note that methods like fadeTo, fadeIn, fadeOut, slideDown, slideUp and
animate 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 in
the element hiding in an instant.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[jQuery edge delegate method has arrived]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-edge-delegate-method-has-arrived"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-edge-delegate-method-has-arrived.png"/>
      <id>https://www.bigbinary.com/blog/jquery-edge-delegate-method-has-arrived</id>
      <published>2010-02-02T00:00:00.000Z</published>
      <updated>2010-02-02T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-edge-delegate-method-has-arrived.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[jQuery delegate method can be used instead of live. In many cases it is desirable to use delegate over live. This blog discusses how delegate works and why it is preferred over live.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-edge-delegate-method-has-arrived"><![CDATA[<p>One of the issues with live method is that live method first searches through
all 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 the
result 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 then
follow
<a href="http://forum.jquery.com/topic/jquery-live-jquery-fn-live-discussion">this thread</a>
.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[jQuery show method edge case]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-show-method-edge-case"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-show-method-edge-case.png"/>
      <id>https://www.bigbinary.com/blog/jquery-show-method-edge-case</id>
      <published>2010-01-29T00:00:00.000Z</published>
      <updated>2010-01-29T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-show-method-edge-case.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[This blog discusses an edge case with jQuery's show method.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-show-method-edge-case"><![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 css
is .</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 no
idea where the element should have display property <code>inline</code> or <code>block</code>. So
jQuery attempts to find out the display property of the element by asking
browser 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 display
property of this newly added element. Whatever is the return value jQuery
applies 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 p
elements are inline. So when jQuery added a new p element to body and asked
browser for the display property, browser replied 'inline' and 'inline' was
applied 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 jQuery
added a p element to body and asked for display type, browser correctly replied
as '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 the
right display property.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[jQuery fadeTo method fades even the hidden elements]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-fadeto-method-fades-even-the-hidden-elements"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-fadeto-method-fades-even-the-hidden-elements.png"/>
      <id>https://www.bigbinary.com/blog/jquery-fadeto-method-fades-even-the-hidden-elements</id>
      <published>2010-01-29T00:00:00.000Z</published>
      <updated>2010-01-29T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-fadeto-method-fades-even-the-hidden-elements.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[This blog discusses how jQuery's fadeTo method fades even the hidden elements and the impact of it.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-fadeto-method-fades-even-the-hidden-elements"><![CDATA[<p><em>Following code has been tested with jQuery 1.4.1 . Code demo links are the end
of the blog .</em></p>
<p><a href="http://api.jquery.com/fadeTo">fadeTo</a> method of jQuery ,strangely, fades event
the 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. Here
is <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 of
zero, while other elements will go down towards zero.</p>
<p>Checkout the same demo in slow motion and notice that while the first p element
emerges out of hiding, the other p element is slowing fading. This might cause
unwanted 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 type="text"><![CDATA[How animate really works in jQuery]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/how-animate-really-works-in-jquery-simple-animation-case-discussed"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-animate-really-works-in-jquery-simple-animation-case-discussed.png"/>
      <id>https://www.bigbinary.com/blog/how-animate-really-works-in-jquery-simple-animation-case-discussed</id>
      <published>2010-01-25T00:00:00.000Z</published>
      <updated>2010-01-25T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-animate-really-works-in-jquery-simple-animation-case-discussed.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[A deep dive into how jQuery pulls of animation tricks.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/how-animate-really-works-in-jquery-simple-animation-case-discussed"><![CDATA[<p>jQuery has <a href="http://api.jquery.com/animate">animate method</a> which is just
awesome. Today I looked into jQuery source code to see exactly how animate
works.</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> is
constantly changing. Based on the value of <code>t</code>, value of <code>n</code> will change. Some
of 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 the
default 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 the
line 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, n
and duration. When all of it was supplied then <code>pos</code> would be derived. The value
of <code>pos</code> over the period of animation would change and it would be something
like 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> method
is 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 actually
applied to the element.</p>
<p>You will have much better understanding of how animate works if you look at the
source code. I just wanted to know at a high level what's going on and these are
my findings.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[JSON parsing natively in jQuery 1.4 and updates]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3.png"/>
      <id>https://www.bigbinary.com/blog/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3</id>
      <published>2010-01-15T00:00:00.000Z</published>
      <updated>2010-01-15T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Starting with jQuery 1.4 JSON will be parsed natively. This blog looks at the impact it will have.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/handling-json-parsing-natively-in-jquery-1-4-and-what-changed-from-jquery-1-3"><![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 a
popular 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 example
server 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 malformed
JSON structure will be rejected.</p>
<h2>How jQuery 1.3 parses JSON structure</h2>
<p>jQuery 1.3 uses JavaScript’s eval to evaluate incoming JSON structure. Open
firebug 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 eval
converts a valid JSON structure into a JavaScript object. However non JSON
structure can also be converted into JavaScript object.</p>
<p>JSON specification says that all string values must use double quotes. Single
quotes are not allowed. What it means is that following JSON structures are not
valid 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 produce
a valid JavaScript object. Since jQuery 1.3 uses eval on strings to convert JSON
structure 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 the
security. It is possible that eval could execute some malicious code. Secondly
it is not as fast as native parse methods made available by browsers. However
browsers 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 not
parse 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 JSON
structures will fail.</p>
<p>In order to ensure that JSON is correctly parsed by the browsers, jQuery does
some code cleanup to make sure that you are not trying to pass something
malicious. You will not be able to test this thing directly using firebug but if
you make an AJAX request and from server if you send response then you can
verify the following code.</p>
<p>Following JSON structure will be correctly parsed in jQuery 1.3 . However the
same JSON structure will fail in jQuery 1.4 . Why? Because of dangling open
bracket <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 the
security issue with JSON parsing before sending that data to browser for
parsing. 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.js
if (/^[\],:{}\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 parsed
by 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 at
this blog titled <a href="http://dbj.org/dbj/?p=470">Cross Browser JSON parsing</a> to get
more 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 send
the 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 not
available 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 strings
to see which one is valid JSON and which one is not.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[How jQuery 1.4 fixed rest of live methods]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/how-jquery-1-4-fixed-rest-of-live-methods"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-jquery-1-4-fixed-rest-of-live-methods.png"/>
      <id>https://www.bigbinary.com/blog/how-jquery-1-4-fixed-rest-of-live-methods</id>
      <published>2010-01-14T00:00:00.000Z</published>
      <updated>2010-01-14T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-jquery-1-4-fixed-rest-of-live-methods.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[When jQuery live was introduced it did not support all elements. Support for those elements came in jQuery 1.4 . This blog looks at how jQuery 1.4 provided support for the remaining elements.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/how-jquery-1-4-fixed-rest-of-live-methods"><![CDATA[<p>If you look at jQuery 1.3 documentation for <code>live</code> method you will notice that
the 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 these
methods in jQuery. If you want a little background on what is <code>live</code> method and
how it works then you should read
<a href="https://www.bigbinary.com/blog/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 in
compliance 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 implemented
DOMFocusIn/DOMFocusOut . However IE implemented <code>focusin</code> and <code>focusout</code> and IE
made 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 used
with 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 is
between <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 applies
fix for these two events, jQuery needs a way to detect if a browser allows
submit and change events to bubble or not. jQuery team does not favor browser
sniffing. 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 is
supported 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 be
used 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 ,based
on 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 tracker
which 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 any
change 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 two
values are matched to see if really a change has happened. Here is code for
detecting 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 delegation
		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 );
			}
		},

		// 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 anymore
		beforeactivate: 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 a
submit button or an image button. Additionally one can hit 'enter' using
keyboard 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 the
submit 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 getting
sorted out. A big <code>Thank You</code> to Justin Meyer of
<a href="http://javascriptmvc.com">JavaScriptMVC</a> who submitted most of the patch for
fixing this vexing issue.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Calling a method on a jQuery collection]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection.png"/>
      <id>https://www.bigbinary.com/blog/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection</id>
      <published>2010-01-12T00:00:00.000Z</published>
      <updated>2010-01-12T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[How do you invoke a method on a jQuery collection.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/hidden-feature-of-jquery-calling-a-method-on-a-jquery-collection"><![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 pass
since 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 the
below 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 type="text"><![CDATA[Use end more often in jQuery while building DOM elements]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/use-end-more-often-in-jquery-while-building-dom-elements.png"/>
      <id>https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements</id>
      <published>2009-11-11T00:00:00.000Z</published>
      <updated>2009-11-11T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/use-end-more-often-in-jquery-while-building-dom-elements.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[In jQuery we chain operations but we can also use end to backtrack a bit. This allows us to chain even more.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/use-end-more-often-in-jquery-while-building-dom-elements"><![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 of
times 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 type="text"><![CDATA[livequery in jQuery]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery.png"/>
      <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>
      <published>2009-10-14T00:00:00.000Z</published>
      <updated>2009-10-14T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[jQuery's live method is amazing. But how it does really work internally. This blog looks at how jQuery pulls off this magic.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery"><![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 to
jQuery 1.3 . It works just great. Except when it does not work. As per the
documentation 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>. jQuery
stores such binding information as <code>data</code> attribute of the bound element. This
is 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 click
behavior. 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 new
click 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 an
element are stored as the data attribute of that element. Well, live is
different. live events are not bound to the element directly. They are bound to
the 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 handlers
are 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 that
event should not be stopped while it is propagating to document. If event
propagation is stopped then event handlers bound at the document level will
never 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. Loosely
translated 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 then
that event is captured by document and necessary action is taken if the target
element matches.</p>
<p>It is clear that if the click event is stopped before it reaches document then
live 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 working
great. 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 document
then 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 and
submit which do bubble in IE will not work in IE. However note that these events
will 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 is
bubbling then live will not work.</li>
<li>IE does not support bubbling for certain events. live method on those events
will 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 finally
merged into jQuery as live method. livequery plugin solves both the problems
listed 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 though
event propagation is being stopped. Also even though change event does not
bubble in IE, above code works in IE.</p>
<p>livequery works because livequery ,unlike live, method does not do binding at
the document level. livequery does binding at the element level. You can find
that 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 not
produce 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 and
then binds the matched element with the event.</p>
<p>By understanding the internals of how live and livequery are implemented, now
you can choose to use livequery in certain cases where live will not work. Also
it 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 document
level.</p>
<p>However when <code>$('p').live(...)</code> is evaluated then jQuery first goes and finds
all 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 found
without using them. What a waste.</p>
<p>If your application has a lot of live methods and this might slow down the
performance 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.

~~~javascript
var 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 is
much better.</p>
<h2>Seeing is believing</h2>
<p>In the previous section, I showed how live method can be made to work without
first selecting the elements. However a friend of mine asked me if I could
conclusively prove that in the real live method a find is <em>actually</em> done. And
in 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 am
overriding the original find method. I will put a log message before passing the
find 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 find
is 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 type="text"><![CDATA[Wrapping functions with self invoking jQuery]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace.png"/>
      <id>https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace</id>
      <published>2009-09-03T00:00:00.000Z</published>
      <updated>2009-09-03T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Wrap your function with self invoking jQuery instead of performing find/replace.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/wrap-your-function-with-self-invoking-jquery-instead-of-performing-find-replace"><![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 Prototype
library. After adding the Prototype library my code starts failing. I have been
asked 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="https://www.bigbinary.com/blog/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 type="text"><![CDATA[Understanding this in Javascript object literal]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/understanding-this-in-javascript-object-literal"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/understanding-this-in-javascript-object-literal.png"/>
      <id>https://www.bigbinary.com/blog/understanding-this-in-javascript-object-literal</id>
      <published>2009-08-06T00:00:00.000Z</published>
      <updated>2009-08-06T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/understanding-this-in-javascript-object-literal.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[this is an important concept in JavaScript and meaning of this could be hard to understand in some cases. This blog take a look at what this is.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/understanding-this-in-javascript-object-literal"><![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 and
it 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 is
not 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 changing
the implementation of method <code>second</code>. Now this method would return another
function.</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> at
the 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 temporary
variable and the inner function should use that temporary variable. This
solution 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 type="text"><![CDATA[jQuery custom events]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-custom-events"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-custom-events.png"/>
      <id>https://www.bigbinary.com/blog/jquery-custom-events</id>
      <published>2009-07-31T00:00:00.000Z</published>
      <updated>2009-07-31T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-custom-events.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[What are jQuery custom events. How to build them. How to use them. This blog discusses all that and much more.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-custom-events"><![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 something
should happen. For example hover, click, focus, mouseover etc are basic events
which 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 an
event. For example, if we want an alert message when we click on a link then
that 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 to
help us, we are going to see it shortly. First let's take a look at a basic
calendar application.</p>
<p>This is a simple javascript calendar which primarily does four things: render
calendar itself, pull data from API and update calendar with API data, ability
to 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 out
and 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 the
main element are laid out. In this case just one look at the code tells me that
four actions can be performed on the main element. This was not so obvious from
the 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. Traditional
javascript programming has been too obsessed with the elements that is clicked
or submitted that causes an action. The emphasis has been too much on keeping
the code around the element that creates an action. In this case the code has
been 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 that
function is always an event handler. In the below example I am passing only one
parameter even though the function takes two parameters: event handler element
and 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 type="text"><![CDATA[jQuery base code to create a jQuery plugin]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-base-code-to-create-a-jquery-plugin"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-base-code-to-create-a-jquery-plugin.png"/>
      <id>https://www.bigbinary.com/blog/jquery-base-code-to-create-a-jquery-plugin</id>
      <published>2009-07-24T00:00:00.000Z</published>
      <updated>2009-07-24T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-base-code-to-create-a-jquery-plugin.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[If you are creating a jQuery plugin then this base code will get you started.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-base-code-to-create-a-jquery-plugin"><![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 jQuery
plugin.</p>
<p><a href="http://gist.github.com/154375">Take a look</a> here .</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Inspecting jQuery internals and storing information]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/jquery-data-for-inspecting-jquery-internals-and-for-storing-information"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-data-for-inspecting-jquery-internals-and-for-storing-information.png"/>
      <id>https://www.bigbinary.com/blog/jquery-data-for-inspecting-jquery-internals-and-for-storing-information</id>
      <published>2009-07-23T00:00:00.000Z</published>
      <updated>2009-07-23T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/jquery-data-for-inspecting-jquery-internals-and-for-storing-information.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Use jQuery.Data for inspecting jQuery internals and for storing information.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/jquery-data-for-inspecting-jquery-internals-and-for-storing-information"><![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 file
which 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 be
to go through all the included javascript files.</p>
<p>However it would be cool if there is a way to find all the click handlers
associated with an element.</p>
<p>jQuery has <a href="http://docs.jquery.com/Internals/jQuery.data">data method</a> which it
uses internally to store information. jQuery uses data method to store all the
handlers associated with an element. We could use this information to our
advantage. Here I am trying to find out all the click handlers associated with
the 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 information
about an element. For example, in an application you need to store information
about people. In the html page you are only displaying names. And when a name is
clicked 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 retrieve
it when username is clicked.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Event propagation and peventDefault]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/event-propagation-and-peventdefault"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/event-propagation-and-peventdefault.png"/>
      <id>https://www.bigbinary.com/blog/event-propagation-and-peventdefault</id>
      <published>2009-07-20T00:00:00.000Z</published>
      <updated>2009-07-20T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/event-propagation-and-peventdefault.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[DOM propagates events and JavaScript can intercept those events and can act on it. Concepts like preventDefault in jQuery could be confusing. This blog discusses that.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/event-propagation-and-peventdefault"><![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 click
on element p will propagate outward and it will be caught by element div which
has 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 things
you need to do is to <code>return false</code> so that the click operation does not perform
its 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 the
default 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 first
line in the function. If I switch the order of e.preventDefault and alert
message in the above javascript then it does not work in Firefox/mac</em>.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[Functional scope in Javascript]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me.png"/>
      <id>https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me</id>
      <published>2009-06-30T00:00:00.000Z</published>
      <updated>2009-06-30T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[What is functional scope. This blog discusses that in the context of JavaScript.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/functional-scope-in-javascript-and-how-javascript-continues-to-surprise-me"><![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 100
but the answer is 11. That's because the scope of a local variable in Javascript
is not limited to the loop. Rather the scope of a local variable is felt all
over the function.</p>
<p>Before you look at the next piece of code remember that defining a variable
without 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 not
matter where the variable is defined. As long as the variable is defined
anywhere within a function then that variable will be set to <code>undefined</code>. It is
when 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 my
attention and for discussing it.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[JS tip - Avoiding polluting the global namespace]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/javascript-tip-do-not-pollute-global-namespace-with-utility-functions"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/javascript-tip-do-not-pollute-global-namespace-with-utility-functions.png"/>
      <id>https://www.bigbinary.com/blog/javascript-tip-do-not-pollute-global-namespace-with-utility-functions</id>
      <published>2009-03-18T00:00:00.000Z</published>
      <updated>2009-03-18T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/javascript-tip-do-not-pollute-global-namespace-with-utility-functions.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[Polluting global namespace is not good. This blog presents a better technique.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/javascript-tip-do-not-pollute-global-namespace-with-utility-functions"><![CDATA[<p>I am learning Javascript and as I do more Javascript work I am learning not only
the language but also the best practices. Today I am developing a Javascript
calendar. In the process of creating the calendar I created a bunch of utility
functions 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 global
namespace. 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 showCalendar
showCalendar({}, 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 global
namespace. It means that if some user has declared a global namespace function
named <code>getCellID</code> then my <code>getCellID</code> is going to collide with the user's
function. 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 at
the 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 showCalendar
showCalendar({}, new Date());

// this call should fail but is not failing now
getCellID(2009, 5, 4);
</code></pre>
<p>The above call to <code>getCellID</code> is currently being executed successfully. It means
I 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 the
variables and functions declared are scoped only to that function. Out of that
function, 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 fail
getCellID(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 global
namespace.</p>
<p>If you notice carefully in the above case after declaring an anonymous function
I am invoking that function by having <code>()</code> at the end. You can read more about
<a href="https://www.bigbinary.com/blog/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function">self-invoking function here</a>
.</p>
]]></content>
    </entry>
  <entry>
      <title type="text"><![CDATA[jQuery Plugin Pattern & self-invoking javascript function]]></title>
      <link rel="alternate" type="text/html" href="https://www.bigbinary.com/blog/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function"/>
      <link rel="enclosure" type="image/png" href="https://www.bigbinary.com/blog/images/social_preview_images/generated/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function.png"/>
      <id>https://www.bigbinary.com/blog/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function</id>
      <published>2009-03-13T00:00:00.000Z</published>
      <updated>2009-03-13T00:00:00.000Z</updated>
      <author>
        <name>Neeraj Singh</name>
        <uri>https://www.bigbinary.com/blog/authors/neerajsingh0101</uri>
      </author>
      <category term="jQuery"/>
      <media:thumbnail url="https://www.bigbinary.com/blog/images/social_preview_images/generated/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function.png" width="1200" height="630"/>
      <summary type="text"><![CDATA[I am learning jQuery and one of things I was struggling with is the plugin pattern. In jQuery world it is very common to wrap the major functionality of the application inside a plugin. This blog discusses how to write a good modular plugin.]]></summary>
      <content type="html" xml:base="https://www.bigbinary.com/blog/understanding-jquery-plugin-pattern-and-self-invoking-javascript-function"><![CDATA[<p>I am learning jQuery and one of things I was struggling with is the plugin
pattern. In jQuery world it is very common to wrap the major functionality of
the 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 jQuery
plugin. The article did a great job of explaining the basics however it took me
a 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 then
invoke it right then and there. Since they are anonymous functions they can't be
invoked twice. However they are a good candidate for initialization work which
is 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 a
variable named hello was created which is a function.</p>
<p>Please note that in the above case only the functions are declared. They are not
invoked. 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 anonymous
function. But before that we need to wrap the whole command in (). Take a look
at this</p>
<pre><code class="language-javascript">// original
function 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 anonymous
function is declared and invoke on run time.</p>
<p>With this understanding now it becomes easier to see what is happening in this
code</p>
<pre><code class="language-javascript">(function ($) {
  // ....
})(jQuery);
</code></pre>
<p>In the above case an anonymous function is being created. However unlike my
anonymous function this anonymous function take a parameter and the name of this
parameter is $. $ is nothing else but jQuery object that is being passed while
invoking this function.</p>
]]></content>
    </entry>
</feed>