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

<channel>
	<title>unitstep.net &#187; jQuery</title>
	<atom:link href="http://unitstep.net/blog/category/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Sun, 08 Jan 2012 23:21:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Triggering links from JavaScript using jQuery</title>
		<link>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/</link>
		<comments>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 00:56:48 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[jquery javascript tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1107</guid>
		<description><![CDATA[Sometimes, you may want to trigger a link (that is, an anchor element) directly from JavaScript. That is, you may want to simulate the user clicking on the link programmatically. If you&#8217;re using jQuery, you&#8217;ll no doubt be aware of the click() method which can be used to trigger that event on an object. One [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, you may want to trigger a link (that is, an <a href="http://htmlhelp.com/reference/html40/special/a.html">anchor element</a>) directly from JavaScript.  That is, you may want to simulate the user clicking on the link programmatically.</p>
<p>If you&#8217;re using jQuery, you&#8217;ll no doubt be aware of the <a href="http://api.jquery.com/click/"><code>click()</code></a> method which can be used to trigger that event on an object.  One would think that executing <code>click()</code> on an anchor element would cause the browser to navigate to the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>, but this isn&#8217;t the case.  <strong>You cannot use jQuery&#8217;s <code>click()</code> method to fully trigger or simulate a user clicking on a link.</strong></p>
<p>Instead, <code>click()</code>, when executed on links, only seems to trigger any event handlers attached to the DOM element rather than any default behaviour.  I&#8217;m not sure if this is the case with other event methods or other DOM elements.</p>
<h2>The solution</h2>
<p>Instead, the solution is to directly manipulate the <code>window.location</code> object from JavaScript.  One would think that since preventing the default action is quite simple (with jQuery&#8217;s <a href="http://api.jquery.com/event.preventDefault/"><code>event.preventDefault()</code></a>), triggering the default action of a link click would also be.  But this isn&#8217;t the case.  Here&#8217;s a simple example on how to simulate a user clicking on a link.</p>
<p>In this contrived example, we have an ordered list of links that we&#8217;ve prevented the default action from executing on each.  Instead, to activate a link we&#8217;ve provided an input box for the user to input the link number and then hit &#8216;Go&#8217;.  When this happens, we grab the identified link and assign the <code>href</code> attribute value of the link to <code>window.location</code>, effectively recreating the default action of clicking the link.</p>
<p><acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> Source:</p>
<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;

  &lt;title&gt;jQuery Demos&lt;/title&gt;
  &lt;link rel="stylesheet" href="styles.css" media="all" /&gt;
  &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="scripts.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;jQuery Demos&lt;/h1&gt;

&lt;ol id="outboundLinks"&gt;
  &lt;li&gt;&lt;a href="http://www.google.com"&gt;Google&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://www.theglobeandmail.com/"&gt;The Globe and Mail&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://stackoverflow.com/"&gt;Stack Overflow&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Link Number to activate:
&lt;input id="linkNumber" type="text" size="3" /&gt;
&lt;input id="activateLink" type="button" value="Go" /&gt;
&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p>JavaScript in <code>scripts.js</code>:</p>
<pre><code>jQuery(function(e)
{
  jQuery("#outboundLinks").click(function(e)
  {
    e.preventDefault();
  });

  jQuery("#activateLink").click(function(e)
  {
    var links = jQuery("#outboundLinks li a");
    var value = parseInt(jQuery("#linkNumber").val());

    if (!isValidNumber(value, links))
    {
      window.alert("Invalid link number.");
      return;
    }
    else
    {
      // This won't work.  We cannot trigger the default
      // behaviour of clicking on a link this way.
      // links.eq(value - 1).click();

      // Instead, manipulate window.location directly.
      window.location = links.eq(value - 1).attr("href");
    }
  });
});

function isValidNumber(value, links)
{
    if (isNaN(value))
    {
      return false;
    }
    else if (value &lt;= 0 || value &gt; links.size())
    {
      return false;
    }
    else {
      return true;
    }
}</code></pre>
<p>Note that <a href="https://developer.mozilla.org/En/DOM/Window.location"><code>window.location</code> is not a regular property</a>; it&#8217;s a special object that when assigned to, changes the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in the address bar of the browser.  There&#8217;s some debate over whether to directly <a href="https://developer.mozilla.org/Talk:en/DOM/window.location">use the location object or to use the <code>window.location.href</code> property</a>.</p>
<p>This accomplishes the task of triggering the default action of clicking on a link, albeit in a roundabout fashion.  Note that this example will only work for regular links that use <code>href</code> attributes as the source of the new <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>.  If you have links doing more complicated things via the use of event handlers (i.e. Ajax), then you&#8217;re better off using <a href="http://api.jquery.com/click/"><code>click()</code></a> or directly invoking the JavaScript methods involved.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>JavaScript Event Delegation</title>
		<link>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/</link>
		<comments>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 03:47:44 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[user interface]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[event delegation]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=720</guid>
		<description><![CDATA[JavaScript Event Delegation is a technique you may have heard of. It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers. I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it. Note that this tutorial will use the [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript Event Delegation is a technique you may have <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">heard of</a>.  It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers.  I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it.  Note that this tutorial will use the great <a href="http://jquery.com">jQuery</a> library (v. 1.3.1) for most examples.</p>
<h3>Delegation</h3>
<p><a href="http://en.wikipedia.org/wiki/Delegation_pattern">Delegation</a> is a fairly well-known design pattern.  In short, it is a way for a method to produce its result simply by calling a method on another object, thus <em>delegating</em> responsibility to that object to provide the functionality needed by the method.  For example, a <code>Cashier</code> object could store a delegate object called <code>Calculator</code>.  Calling <code>Cashier.addToTotal(value)</code> would simply delegate to the contained object, calling <code>Calculator.addToTotal(value)</code>.  </p>
<p>How is delegation different than <em>inheritance</em>?  With inheritance, the subclass inherits all of the functionality/behaviour of the parent class.  You may not want or need this; in the preceding example, it would not make sense to have <code>Cashier</code> extend from <code>Calculator</code> simply because we wanted the <code>addToTotal()</code> behaviour/functionality.  Delegation allows the behaviour advertised by a certain object/class to be provided by another.</p>
<h3>Traditional Event Handling</h3>
<p>In order to understand event delegation in JavaScript, we should first look briefly at how events are handled traditionally.  When I talk of <em>traditional event handling</em>, I am referring to the model that most will know.  In this model, functions are <strong>individually</strong> bound to events of certain elements.  For example, to make all links turn bold upon clicking them (and prevent them from being followed), we could use some JavaScript like this:</p>
<pre><code>window.onload = function()
{
  links = document.getElementsByTagName('a');
  for (var i = 0; i &lt; links.length; ++i)
  {
    links[i].onclick = makeBold;
  }

}

function makeBold()
{
  this.style.fontWeight = 'bold';
  return false;
}</code></pre>
<p>The key point with this example is that the function <code>makeBold()</code>, our <em>event handler</em>, is <strong>bound to each and every</strong> <code>a</code> element.  From a resource point of view, this is may be a bad thing because the more event handlers that are attached, the more memory that is used, in general.</p>
<p>Of course, I promised I&#8217;d be using jQuery, and doing so cleans up the above code substantially, as well as making it cross-browser compatible: (Besides adding a ton of other abilities and making life easier)</p>
<pre><code>jQuery(function()
{
  jQuery('a').click(makeBold);
});

function makeBold(e)
{
  e.preventDefault();
  jQuery(this).css('font-weight', 'bold');
}</code></pre>
<p>While this code is cleaner, it still does basically the same thing as above, that is, the event handler function <code>makeBold()</code> is bound to <strong>each</strong> matched element, that is, each <code>a</code> element.</p>
<p>As a final note, don&#8217;t confuse my use of the term <em>traditional</em> with <a href="http://www.quirksmode.org/">Peter-Paul Koch&#8217;s</a> excellent guide to JavaScript event registration, where he uses the term <a href="http://www.quirksmode.org/js/events_tradmod.html"><em>traditional</em> to refer to one <em>method</em> of event registration</a>, distinct from inline registration and the later <a href="http://www.w3.org/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="World Wide Web Consortium">W3C</acronym></a> and Microsoft &#8220;Advanced&#8221; event registration models.</p>
<h3>Event handling using delegation</h3>
<p>By contrast, <strong>event delegation</strong> uses a single (or comparatively few) event handlers to implement the behaviour required.  This takes advantage of two key features of JavaScript events, namely <strong><a href="http://www.quirksmode.org/js/events_order.html#link3">event bubbling</a></strong> and the <strong><a href="http://docs.jquery.com/Events/jQuery.Event#event.target">target event</a></strong>.</p>
<p><strong>Event bubbling</strong> is a model for how events take place on the page.  It grew out of a need to resolve the order in which events were triggered on ancestor and descendant elements.  For example, assume that I have two event handlers, one attached to the &#8220;click&#8221; event of a <code>div</code> and another attached to the &#8220;click&#8221; event of an <code>a</code> element <strong>within</strong> that <code>div</code>.  If I click the <code>a</code> element, which event fires first?  Event bubbling is one way to solve that question: It states that the event on the <strong>inner</strong> element happens <em>first</em>, and then the event &#8220;bubbles&#8221; upwards to trigger events on ancestor or container elements.  There is another opposing model that works in the opposite way, but bubbling seems to be better supported and is more relevant for this article.</p>
<p>Here&#8217;s a crude diagram of event bubbling, using a pseudo-<a href="http://www.w3.org/TR/CSS21/box.html"><acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> box model</a> of sorts:</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/02/javascript-event-delegation.png" alt="Event Bubbling Diagram" title="Event Bubbling Diagram" width="302" height="228" class="size-full wp-image-747" /><br />
Event bubbling diagram
</p>
<p>The <strong>event target</strong> is the DOM element that issued the event, or the originating element.  This is why I believe it&#8217;s a confusing term, since it would make more sense to called it the <em>event source</em>.  But I digress.  The <a href="https://developer.mozilla.org/En/DOM/Event">event object</a>, passed to an event handler as an argument (or available via <code>window.event</code>, though jQuery normalizes this) contains a property, <code>event.target</code>, that allows you to get the reference to the &#8220;target&#8221; element that the event started bubbling up from.</p>
<h3>How it&#8217;s implemented</h3>
<p>All of this is typically accomplished by registering a single event handler to a &#8220;container&#8221; element that holds all of the elements we wish to react to events for.  When an event is triggered on one of the inner elements, it &#8220;bubbles up&#8221; to the container element, where it triggers the event handler function.  From there, we can inspect the source of the event (confusingly called the <em>event target</em>) and then react accordingly.</p>
<p>This is where the delegation aspect comes into play.  Since the container element may hold many inner elements, it is unlikely that we would want the same behaviour for each element when an event was triggered on it.  For example, we might want certain <code>a</code> elements to trigger one action when clicked, while wanting another set of <code>a</code> elements to trigger another action.  We&#8217;d typically differentiate these links by using separate class names or by context and then attaching event handlers as appropriate.</p>
<p>Using event delegation, process is similar, but instead of attaching multiple event handlers we have one on the overall parent element.  When this event handler is triggered, we determine which element triggered the event and then based on this, delegate the remainder of the processing to another function.  An example would be helpful now, as our previous examples with making some text bold weren&#8217;t too useful.  Here&#8217;s the <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> fragment for the container and elements.</p>
<pre><code >&lt;div class="container"&gt;
&lt;ul class="top"&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item A - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item B - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item C - Click to remove&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item D - Click to remove&lt;/a&gt;&lt;/li&gt;
&lt;/div&gt;</code></pre>
<p>And here&#8217;s the JavaScript:</p>
<pre><code>jQuery(function()
{
  jQuery('div.container').click(handleEvent);
});

function handleEvent(e)
{
  // Obtain the source element through event.target.
  var target = jQuery(e.target);

  // Now decide what to do with it.
  if (target.is('a.expandList'))
  {
    // We use Function.call() to set the context for the `this` keyword.
    return expandList.call(target, e);
  }
  else if (target.is('a.remove'))
  {
    return remove.call(target, e);
  }
  else
  {
    // Otherwise, allow the default action to take place.
    return true;
  }
}

function expandList(e)
{
  e.preventDefault();

  // The `this` keyword now references the jQuery object representing the
  // target, since that is what we set the context to.
  jQuery(this).parent('li').find('ul.hide').slideToggle('fast');
}

function remove(e)
{
  e.preventDefault();
  jQuery(this).parent('li').fadeOut('normal', function(){jQuery(this).remove()});
}</code></pre>
<p>With this example, the steps are clearly outlined.  First, we attach the overall event handler to the container element; events that take place on its inner or children element will bubble up to it.  When an event is received, we inspect <code>event.target</code> to determine the origin and based on that, &#8220;hand off&#8221; to another function to carry out the proper behaviour. </p>
<p>With some standardization of the <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> class names you use and the associated event handler function names, you can clean up this code to reduce duplication and turn it into a design pattern of sorts.  In fact, that&#8217;s <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">exactly what Dan Webb has done</a>.</p>
<h3>More advantages of event delegation</h3>
<p>Besides potentially using less resources by having less event handlers bound, event delegation brings one other significant advantage: <strong>The ability to have event handlers &#8220;auto bind&#8221; to new DOM elements</strong>.  For example, let&#8217;s say we were to dynamically update the DOM and add more list items to our previous example; this sort of action happens frequently during Ajax operations where you want to present new content to the user.  </p>
<p>In the &#8220;traditional&#8221; event handling model, the new elements <strong>would not automatically respond to events</strong> as you would like.  This is because the events were individually bound to each element.  This is <a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">a well known problem</a>.  However, in event delegation, since there&#8217;s only one event handler bound to the <strong>container or ancestor element</strong>, the newly-created elements will respond to the event properly! This is because an event on them &#8220;bubbles&#8221; up to the container element just as for the original elements.</p>
<h3><a href="/projects/javascript-event-delegation/javascript-event-delegation.html">Demo of Event Delegation</a></h3>
<p>Perhaps <a href="/projects/javascript-event-delegation/javascript-event-delegation.html">a little demo</a> is needed.  With this demo, you can see both the implementation of event delegation as well as the effect of adding new elements.</p>
<h3>Drawbacks of event delegation</h3>
<p>I&#8217;ve already talked about some of the benefits (fewer bound event handlers, so less resources used and the ability to adapt with DOM changes), but it&#8217;s worthwhile to iterate over some of the drawbacks.  </p>
<ol>
<li>Firstly, not all elements &#8220;bubble up&#8221; in the way described.  The <code>blur</code>, <code>focus</code>, <code>change</code> and <code>submit</code> are notable exceptions so you will not be able to use event delegation with these events in the manner described in this article.</li>
<li>Furthermore, the code developed to maintain event delegation can be more complicated to understand than with just using the traditional model.  Indeed, there is an initial investment time everyone must make to get going.  This should obviously be considered since code maintenance is always important.</li>
<li>Because there&#8217;s one event handler being called for all events on inner/descendant elements, there can be some performance implications.  If you&#8217;re calling expensive functions within this event handler, the event processing could slow down significantly.  Careful optimization may be required.</li>
</ol>
<p>However, some of these drawbacks can be mitigated by using solutions developed by the jQuery community.  Even though event delegation is somewhat new, there are already plugins available that take a lot of the grunt-work out of event delegation, abstracting away the details and making things easier for you.  Even jQuery itself also supports event delegation through a built-in function as of v1.3.  Here are some options for pre-built solutions:</p>
<ul>
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Dan Webb&#8217;s Delegate Plugin</a><br />
This is a fairly straightforward way to implement delegation and it&#8217;s easy to setup and understand.</li>
<li><a href="http://docs.jquery.com/Events/live#typefn">jQuery&#8217;s built in <code>live()</code> function</a><br />
This supports a subset of events but is good enough for most uses.</li>
<li><a href="http://plugins.jquery.com/project/livequery">The Live Query plugin</a><br />
This is your best bet if you need the most functionality, though I haven&#8217;t personally tried it out yet.</li>
</ul>
<h3>Conclusion</h3>
<p>Delegation nicely solves the problem of having to rebind events after adding new elements to the DOM.  For that reason alone, I&#8217;ve started to use in my work more often.  At its heart, it&#8217;s a useful design pattern, but should be only with full understanding of the pros and cons.  I hope you enjoyed reading this article!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Event Delegation Made Easy</a></li>
<li><a href="http://usabletype.com/weblog/event-delegation-without-javascript-library/">Event delegation without a JavaScript library</a></li>
<li><a href="http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/">JavaScript Event Delegation is Easier than You Think</a></li>
<li><a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">Why do my events stop working after an <acronym class="uttAcronym" title="Asynchronous Javascript And XML">AJAX</acronym> request?</a></li>
</ol>
<h4>Revisions</h4>
<ul class="note less">
<li>2009-02-20: Added a crude diagram of event bubbling</li>
</ul>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Upgrade jQuery for better Opera support (Or just upgrade Opera)</title>
		<link>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/</link>
		<comments>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/#comments</comments>
		<pubDate>Thu, 26 Jun 2008 00:45:43 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[browsers]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[opera]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=336</guid>
		<description><![CDATA[I ran into a weird problem while testing one of my sites that used jQuery with Opera 9.26. (I happened to be using this older version of Opera because I am lazy to upgrade; I&#8217;m still using Firefox 2 despite the successful launch of FF3) The issue was with an Ajax request I was sending. [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into a weird problem while testing one of my sites that used jQuery with Opera 9.26.  (I happened to be using this older version of Opera because I am lazy to upgrade; I&#8217;m still using Firefox 2 despite the successful launch of FF3)</p>
<p>The issue was with an Ajax request I was sending.  The return value was an array in JSON form.  More specifically, the server was returning something like:</p>
<pre><code>{tag:[{id1:'A',id2:'B'}, {id1:'A',id2:'B'}, {id1:'A',id2:'B'}]}</code></pre>
<p>This was perfectly valid and worked fine in both Firefox and Internet Explorer.  However, in Opera 9.26, I got a JavaScript error indicating that the JSON was not valid.  It was then that I realized I was using an older version of jQuery, v1.2.2.  <a href="http://docs.jquery.com/Downloading_jQuery">Upgrading to the latest</a>, 1.2.6 fixed the problem.  Strangely, I could not find anything on their bug tracker indicating that such a problem (JSON and Opera) had been fixed.</p>
<p>What was even more interesting was that <a href="http://www.opera.com/download/">upgrading to Opera 9.50</a> also solved the problem independently; that is, things worked fine even with the older version of jQuery.  This goes to show the importance of keeping your software up to date and highlights the complicated interactions between different browsers and client-side code in a web application. </p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/06/25/upgrade-jquery-for-better-opera-support-or-just-upgrade-opera/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Share This in jQuery</title>
		<link>http://unitstep.net/blog/2007/08/01/share-this-in-jquery/</link>
		<comments>http://unitstep.net/blog/2007/08/01/share-this-in-jquery/#comments</comments>
		<pubDate>Thu, 02 Aug 2007 04:35:29 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[plugins]]></category>
		<category><![CDATA[wordpress]]></category>

		<guid isPermaLink="false">http://unitstep.net/blog/2007/08/01/share-this-in-jquery/</guid>
		<description><![CDATA[Share This is an excellent WordPress plugin written by Alex King. The plugin provides a neat and customizable pop-up menu for allowing readers to easily share one of your blog posts using many of the social bookmarking or social websites out there. It&#8217;s an intelligent solution to the problem of having too many sharing icons [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><a href="http://alexking.org" title="Share This icon Copyright Alex King"><img src='http://unitstep.net/wordpress/wp-content/uploads/2007/08/share-icon-128x128.png' alt='Share This icon Copyright Alex King (http://alexking.org)' /></a></p>
<p><a href="http://alexking.org/projects/wordpress">Share This</a> is an excellent WordPress plugin written by <a href="http://alexking.org/">Alex King</a>.  The plugin provides a neat and customizable pop-up menu for allowing readers to easily share one of your blog posts using many of the social bookmarking or social websites out there.  It&#8217;s an intelligent solution to the problem of having <a href="http://www.pronetadvertising.com/articles/why-too-many-little-icons-can-easily-distract-your-visitors.html">too many sharing icons</a> that may potentially distract or irritate readers.</p>
<p>Since launching, Share This has become <a href="http://alexking.org/blog/2006/12/27/share-this-catching-on">very popular</a>, with many blogs using it.  I recently began using the plugin for a site of mine, and was impressed by its usefulness. (And the <a href="http://alexking.org/blog/2006/12/11/shareiconscom">icon project it launched</a>)  However, I had also decided to use the <a href="http://jquery.com">jQuery</a> JavaScript framework (and its <a href="http://docs.jquery.com/Plugins">plugins</a>) for this site, and since Share This uses <a href="http://www.prototypejs.org/">Prototype</a> for its JavaScript functionality, there were some conflicts.  </p>
<p>So, I decided to do a minor re-write of Share This, altering only the JavaScript portion to use jQuery instead of Prototype.</p>
<h3>jQuery?</h3>
<p>I wanted to stick with jQuery for a variety of reasons, but mainly because I have more experience with it than with Prototype.  I won&#8217;t get into an argument over which of the frameworks is better, and will instead stick to the &#8220;Unto each his own&#8221; line of thinking.</p>
<p>While jQuery generally works well with existing JavaScript, as it doesn&#8217;t alter the global namespace, and additionally has a &#8220;no-conflict&#8221; mode, some of the plugins that I wanted to use (specifically <a href="http://jquery.com/demo/thickbox/">Thickbox</a>) weren&#8217;t written for the no-conflict mode.  The issue stems from the use of the &#8220;<code>$</code>&#8221; variable name.  In jQuery, it&#8217;s a shortcut for the be-all-end-all function <code>jQuery()</code>, while in Prototype, it&#8217;s a shortcut for <code>document.getElementById()</code>.</p>
<h3>Share This in jQuery</h3>
<p>Before I offer the download, I want to make it clear that this was a <strong>very minor</strong> change &#8211; no functionality was added or removed, as just the JavaScript portion was re-written (quickly) to support jQuery instead of Prototype.  Again, it&#8217;s not better than the original <a href="http://alexking.org/projects/wordpress">Share This</a>, only different.  Furthermore, 100% full credit still belongs to <a href="http://alexking.org/">Alex King</a>, as this is barely a derivative work.</p>
<p>In order to use this version, you will need the <a href="http://docs.jquery.com/Downloading_jQuery">jQuery framework</a> as well as the <a href="http://jquery.com/plugins/project/dimensions">Dimensions plugin</a>.  Their cumulative compressed sizes are comparable to the compressed size of the Prototype framework.  You will need to link them to your site in your WordPress theme&#8217;s <code>header.php</code> file by adding lines like these, preferably between the <code>head</code> tags.</p>
<pre><code>&lt;script type="text/javascript" src="/path-to-jquery/jquery.pack.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="/path-to-jquery-dimensions/jquery.dimensions.pack.js"&gt;&lt;/script&gt;</code></pre>
<p>You can then replace the original <code>share-this.php</code> with the jQuery version in the <a href='/wordpress/wp-content/uploads/2007/08/share-this-14-jquery.zip' title='Share This in jQuery'>zipped download</a>.  (You may want to backup the original file first, as always)</p>
<h3>Download</h3>
<ul>
<li><a href='/wordpress/wp-content/uploads/2007/08/share-this-14-jquery.zip' title='Share This in jQuery'><img src="/images/icons/silk/folder_go.png" alt="Download" />Share This 1.4 for jQuery</a></li>
</ul>
<h3>Credit and Misc.</h3>
<p>As mentioned before, all credit still belongs to Alex King for writing Share This in the first place.  I haven&#8217;t really changed anything, just adapted it to work with jQuery and thought I&#8217;d like to make it available for everyone to use.  It still works exactly as before, so configuring options and so forth isn&#8217;t any different.</p>
<p>What I changed was just the part of the plugin that outputs the JavaScript necessary to make Share This work.  It&#8217;s just been changed to use jQuery instead of Prototype.  I also commented out the parts of the plugin that link the Prototype framework (from WordPress) into the header.  As mentioned before, you&#8217;ll have to link in the requisite jQuery script files yourself.  Since it looks like <a href="http://trac.wordpress.org/ticket/3824">WordPress will be moving over to jQuery</a>, at least for the admin pages, this might be something worthwhile.</p>
<p>The JavaScript has been written in jQuery&#8217;s compatibility mode (using <code>jQuery()</code> instead of <code>$</code>), so you can continue to use Prototype on your site if you wish.  As mentioned, this was a very quick rewrite, so not much has changed. </p>
<p>Some people have pointed out that Prototype is a lot larger than jQuery in terms of file size.  This may be somewhat true, but when Prototype v 1.5.0 is <a href="http://dean.edwards.name/packer/">packed</a>, it comes in at only around 27 KB.  jQuery packed is about 21 KB, but with the Dimensions plugin needed to make Share This work with jQuery adds another 4-5 KB, bringing the total size close to that of Prototype.  So why use jQuery? Again, it&#8217;s just because I&#8217;m more familiar with it and like how jQuery expressions are formed, particularly with the ability to <a href="http://docs.jquery.com/How_jQuery_Works#Chainability_.28The_Magic_of_jQuery.29">chain function calls</a>.</p>
<h3>Update</h3>
<p><a href="http://www.thunderguy.com/semicolon/">Bennett McElwee</a>, author of many nice WordPress plugins (including some that I use on my own site), has <a href="http://www.thunderguy.com/semicolon/2007/07/30/share-this-jquery-a-wordpress-plugin/">already released a version of Share This in jQuery</a>, seemingly two days before I published this post &#8211; what a coincidence!  His appears to be more polished, though, as it doesn&#8217;t use the extra Dimensions plugin and also includes some nice effects.  Definitely give it a try.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2007/08/01/share-this-in-jquery/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

