<?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>Blog - ShiftEleven &#187; JavaScript</title>
	<atom:link href="http://shifteleven.com/articles/category/javascript/feed" rel="self" type="application/rss+xml" />
	<link>http://shifteleven.com</link>
	<description></description>
	<lastBuildDate>Mon, 09 Jan 2012 04:04:19 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Mouse Clicks for HTML5 Cavas Entities via Paths</title>
		<link>http://shifteleven.com/articles/2012/01/08/mouse-clicks-for-html5-cavas-entities-via-paths?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mouse-clicks-for-html5-cavas-entities-via-paths</link>
		<comments>http://shifteleven.com/articles/2012/01/08/mouse-clicks-for-html5-cavas-entities-via-paths#comments</comments>
		<pubDate>Mon, 09 Jan 2012 04:04:19 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[HTML & CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[canvas]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=138155</guid>
		<description><![CDATA[The canvas element in HTML5 is exciting because it really opens the doors to games, drawing, and animation. This is especially exciting as browsers hardware accelerate canvas and improve its performance. What isn&#8217;t so exciting though is that you do &#8230; <a href="http://shifteleven.com/articles/2012/01/08/mouse-clicks-for-html5-cavas-entities-via-paths">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>The <code>canvas</code> element in HTML5 is exciting because it really opens the doors to games, drawing, and animation. This is especially exciting as browsers <a title="Unleash the Power of Hardware-Accelerated HTML5 Canvas" href="http://www.htmlgoodies.com/html5/client/unleash-the-power-of-hardware-accelerated-html5-canvas.html">hardware accelerate canvas</a> and improve its performance. What isn&#8217;t so exciting though is that you do have to do a lot more for yourself.</p>
<p>So if you draw something into the canvas, you don&#8217;t get to attach event listeners on the objects you create within the canvas, just on the canvas itself. This means that you have to build your own event system. This isn&#8217;t that difficult if you organize your entities you&#8217;re drawing and rely on&nbsp;<a href="http://www.w3.org/TR/2dcontext/#dom-context-2d-ispointinpath"><code>isPointInPath</code></a> to do the searching for you.</p>
<section>
<h2>Overview</h2>
<p>When you use path methods, like <code>arc</code>, <code>bezierCurveTo</code>, or <code>lineTo</code>, the 2D context keeps track of things really nicely for you. After you add your path, you can ask the context whether or not a point is within the area of said path via the <code>isPointInPath</code> method.</p>
<p>The way to find the object is to render each entity in <strong>reverse</strong> order, draw the path, and then check to see <code>isPointInPath</code>. The reason to go in reverse order is because the most visible, unobstructed object is at the last index in the rendering order.</p>
<p>Paths are great because they are fast, but they are pretty plain. What you if you want to draw images? Well there&#8217;s no rule that you can only use one canvas. This means that you can use one canvas to draw your main stage with images, and then use the light-weight paths to draw the hit detection area.</p>
<p>The <a href="http://shifteleven.com/demo/canvas-hit-detection/">demo</a> will draw the earth and the moon and will print a the name of the selected planet.</p>
</section>
<p><span id="more-138155"></span></p>
<section>
<h2>The Planet Entity Class</h2>
<p>Since we want to manage two different rendering passes, our entity class will have two methods. One to draw the visible image and the other to render the hit detection path.</p>
<pre class="sh_javascript">/**
 * Planet.
 *
 * A planet entity to draw on a canvas.
 */
Planet = function(image, opt_x, opt_y) {
  this.image_ = image;
  this.x_ = opt_x || 0;
  this.y_ = opt_y || 0;
};
/**
 * Draw the planet.
 */
Planet.prototype.draw = function(ctx) {
  ctx.drawImage(this.image_, this.x_, this.y_);
};
/**
 * Draw the hit detection path.
 */
Planet.prototype.drawDetectionPath = function(ctx) {
  ctx.beginPath();
  var radius = this.image_.width / 2;
  ctx.arc(this.x_+radius, this.y_+radius, radius, 0, Math.PI*2, true);
  ctx.closePath();
};</pre>
<p>The <code>drawDetectionPath</code> method draws a circle, which is a pretty good hit detection area for a planet. One thing to note, the path has no fill style nor does it call <code>fill</code>. This is because we&#8217;re not making it visible, we just want the path information.</p>
</section>
<section>
<h2>The Entity Manager</h2>
<p>The entity manager is pretty simple too. The entity manager keeps a list of all the planets to draw. It also performs the logic of trying to identify the entity that exists at an X,Y position in the canvas.</p>
<pre class="sh_javascript">/**
 * Entities Manager.
 *
 * Manage a set of entities to draw them to the screen and to
 * detect mouse hits.
 */
EntitiesManager = function(entities, rendererCtx, detectionCtx) {
  this.entities_ = entities;
  this.rendererCtx_ = rendererCtx;
  this.detectionCtx_ = detectionCtx;
};
EntitiesManager.prototype.draw = function() {
  this.rendererCtx_.clearRect(0, 0, this.rendererCtx_.canvas.width,
                              this.rendererCtx_.canvas.height);
  for (var i = 0; i &lt; this.entities_.length; i++) {
    this.entities_[i].draw(this.rendererCtx_);
  }
};
EntitiesManager.prototype.findEntity = function(x, y) {
  // Clear out the detection canvas.
  this.detectionCtx_.clearRect(0, 0, this.detectionCtx_.canvas.width,
                               this.detectionCtx_.canvas.height);
  // Loop backwards though each entity. After drawing it onto
  // the detection canvas, see if X,Y coordinates from the mouse are
  // within the path drawn onto the canvas.
  for (var i = this.entities_.length-1; i &gt;= 0; i--) {
    var entity = this.entities_[i];
    entity.drawDetectionPath(this.detectionCtx_);
    if (this.detectionCtx_.isPointInPath(x, y)) {
      return entity;
    }
  }
  return null;
};</pre>
<p>To use this class, simply make a new instance of this and pass along an array of planets and the 2 2D canvas context objects. To draw or refresh the display, simply call <code>draw</code>. After you receive a click event on the render canvas, you can pass in the X,Y coordinates into <code>findEntity</code> to see if there are any objects underneath that position. That being said, there&#8217;s a little massaging that needs to happen on the coordinates&nbsp;from the mouse click.</p>
</section>
<section>
<h2>Getting the Mouse Position</h2>
<p>When you listen for the click event on the canvas object, the callback will receive an Event object which will have the X,Y position of the coordinates of where the click happened. The problem with just using those X,Y coordinates are that they aren&#8217;t in the same coordinate space as the coordinate space of the canvas context. Awesomely enough, it&#8217;s easy to rectify. You need to get the coordinates of the mouse click and then subtract the coordinates of top,left point of the canvas element.</p>
</section>
<pre class="sh_javascript">canvasElement.addEventListener('click', function(evt) {
  var rect = renderer.getBoundingClientRect();
  var x = evt.clientX - rect.left;
  var y = evt.clientY - rect.top;

  var entity = entitiesManager.findEntity(x, y);
  // ...
});</pre>
<section>
<h2>About The Demo</h2>
<p>The basics of this code are viewable at <a title="Demo" href="http://shifteleven.com/demo/canvas-hit-detection/">shifteleven.com/demo/canvas-hit-detection/</a>. While it is pretty much the same code that&#8217;s in this blog post, there are a couple of interesting bits to discus.</p>
<h3>Image Manager</h3>
<p>I&#8217;m using images for the earth and the moon. So before I can start drawing with those images, I need to make sure that they are downloaded first. To that end, I use an <code>ImageManager</code> class to download everything and fire a callback when it&#8217;s finished. It&#8217;s not terribly robust, but it gets the job done for the demo.</p>
<h3>Transform Decorator</h3>
<p>To show the performance impact of how many planets are drawn onto the canvas, I needed to draw them in random places and to scale them at different sizes. Rather than adding the transform properties into the <code>Planet</code> entity class, I used a <a href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator</a> to do that dirty work for me. I also only end up making 2 planet instances (one for the earth, the other the moon).</p>
<h3>Performance</h3>
<p>Take it easy before trying to render 100,000 planets onto the canvas as this could take a while. That being said, once you do render all of the planets, notice how fast it is for it to actually find the planet! Paths are pretty fast!<br />
</section>
<script type="text/javascript" src="/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_javascript.js"></script><script type="text/javascript" src="/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_javascript.js"></script><script type="text/javascript" src="/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_javascript.js"></script>]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2012/01/08/mouse-clicks-for-html5-cavas-entities-via-paths/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Aliases with Google Closure</title>
		<link>http://shifteleven.com/articles/2011/08/25/aliases-with-google-closure?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=aliases-with-google-closure</link>
		<comments>http://shifteleven.com/articles/2011/08/25/aliases-with-google-closure#comments</comments>
		<pubDate>Thu, 25 Aug 2011 23:28:18 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[google closure]]></category>

		<guid isPermaLink="false">http://shifteleven.com/?p=937</guid>
		<description><![CDATA[I&#8217;m starting to use the closure library and all of it. The closure compiler is nice because it can compress your JS code down, a LOT. In order to get the biggest bang for your buck. you want to use &#8230; <a href="http://shifteleven.com/articles/2011/08/25/aliases-with-google-closure">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m starting to use the <a title="Google Closure" href="http://code.google.com/closure/">closure library</a> and all of it. The <a title="Google Closure Compiler" href="http://code.google.com/closure/compiler/">closure compiler</a> is nice because it can compress your JS code down, a LOT. In order to get the biggest bang for your buck. you want to use the <a title="Advanced Compilation and Externs" href="http://code.google.com/closure/compiler/docs/api-tutorial3.html">advanced optimization</a> settings. It can eliminate unused code, inline functions, and rename variables.</p>
<p>In order for variable renaming to work, you have to behave by closure&#8217;s rules. One rule closure has is: Let me do the optimization. One of the main reasons for this is that some shortcuts can make it hard to determine your intent.</p>
<p>One shortcut I like to use is to create alias to JavaScript objects that have long names or long <a title="JavaScript Namespaces" href="http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/">namespaces</a>.</p>
<pre class="sh_javascript">(function() {
  var alias = a.very.long.namespace;
  /** @constructor */
  alias.NewClass = function() {};
})();</pre>
<p>Now, to you are I, we can easily tell that I intend to use this self-calling anonymous function as a closure to store my alias; however, how can a compiler know that this was my <em>intent</em>.</p>
<p>Intent is a key concept when you work with the advanced compilation. In the above example, Closure knows that <code>a.very.long.namespace.NewClass</code> is even a class because of the <code>constructor</code> annotation. The way to tell Closure that you intend to make aliases is by using the <code><a title="goog.scope Documentation" href="http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html#goog.scope">goog.scope</a></code> function<a href="#fn-1"><sup>1</sup></a>.</p>
<pre class="sh_javascript">goog.require('goog.dom');
goog.require('goog.events');
goog.require('goog.events.EventType');

goog.scope(function() {
  var dom = goog.dom;
  var events = goog.events;
  var EventType = goog.events.EventType;

  var elem = dom.getElement('myElement');
  events.addEventListener(elem, EventType.CLICK, function() {
    alert('I was clicked');
  });
});</pre>
<p><span id="more-937"></span></p>
<section>
<h2>Behind the Scenes</h2>
<p>So what does Closure do with this info? Well, if your code is not compiled, nothing :) The implementation of <code>goog.scope</code> will just call the function that was passed in as an argument. Now if you took the time to even investigate aliasing, then you probably care about what happens when you run the code through the compiler.</p>
<p>The compiler will actually expand all of your aliased variables into their fully qualified path in one of the compiler passes through the code before sending it to other passes. Think of it as a preprocessing step.</p>
<h3>Caveats</h3>
<p>Since <code>goog.scope</code> is a special function, you should know that it has special rules that you need to follow. They are pretty easy and you probably won&#8217;t run into them unless you&#8217;re doing something sneaky.</p>
<ul>
<li><strong>You&#8217;re not allowed to use <code>this</code></strong>. If you mean to use window here, just use <code>goog.global</code>.</li>
<li><strong>All local variables need to be references to other namespaces or classes</strong>. This is good because it helps you catch potential errors where you made a new variable at that scope when you shouldn&#8217;t have.</li>
<li><strong>You can only assign an alias name once</strong>. This helps avoid bugs too because if you try to reassign a value to an alias, the change won&#8217;t be available when you leave that scope.</li>
<li><strong>You cannot throw an exception from <code>goog.scope</code></strong>. Now you can throw the exception from a function inside of scoping function.</li>
<li><strong>You cannot return a value nor assign <code>goog.scope</code> to anything</strong>. This makes sense because if you&#8217;re assigning and returning, you&#8217;re doing something more than just aliasing and the compiler won&#8217;t be able to figure out what the hell you&#8217;re doing.</li>
</ul>
</section>
<section>
<h2>Conclusion</h2>
<p>To get the biggest bang for your buck out of the Closure compiler, you sometimes need to give it hints about what you intend to do. <code>goog.scope</code> is just one of those ways that you can provide it with some extra context so that it can do its job better. This extra bit of metadata can also help you do your job better too because the Closure compiler will be able to message you about errors when it sees a mismatch between what you intend to be doing, and what you&#8217;re actually doing.</p>
<p>If you would like to read more about the <code>goog.scope</code> proposal and action plan, check out the <a title="Making Closure less verbose with goog.scope" href="https://docs.google.com/document/pub?id=1ETFAuh2kaXMVL-vafUYhaWlhl6b5D9TOvboVg7Zl68Y">implementation document</a>. It also outlines other options considered for solving the aliasing problem and why they were less ideal. Also, feel free to investigate the <a title="ScopedAliases.java Source Code" href="http://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/javascript/jscomp/ScopedAliases.java">compiler source code for <code>goog.scope</code></a>.</p>
</section>
<section>
<h3>Footnotes</h3>
<ol>
<li id="fn-1"> Yes, I know that you can do this with jQuery simply as <code>$('#myElement').click(function() { alert(...); });</code> :p</li>
</ol>
</section>
<script type="text/javascript" src="/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_javascript.js"></script><script type="text/javascript" src="/wp-content/plugins/shjs-syntax-hiliter/shjs/lang/sh_javascript.js"></script>]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2011/08/25/aliases-with-google-closure/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Array-like Objects in JavaScript</title>
		<link>http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=array-like-objects-in-javascript</link>
		<comments>http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript#comments</comments>
		<pubDate>Fri, 29 Jun 2007 01:43:38 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[arguments]]></category>
		<category><![CDATA[array]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=32</guid>
		<description><![CDATA[It make look like an Array, hell, it even has a length attribute; however, it may not actually be an Array. JavaScript is sometimes a quirky language to say the least and the notion of what is an Array is &#8230; <a href="http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>It make look like an Array, hell, it even has a length attribute; however, it may not actually be an Array.  JavaScript is sometimes a quirky language to say the least and the notion of what is an Array is no exception.</p>
<p>So what are these array-like objects that I speak of?  Well there are a few of them, one of which is <code>arguments</code>.  <code>arguments</code> is a special variable that is available inside the body of every function.  It is in fact, the list of arguments that were passed in.</p>
<p><span id="more-32"></span></p>
<h3><code>arguments</code></h3>
<p>If you inspect the <code>arguments</code> variable in a tool such as <a href="http://www.getfirebug.com,">Firebug</a> you will notice that it prints out like an array.  It has elements in sequential order and it even has a <code>length</code> property.</p>
<pre class="ruby" title="code">var testFunction = function() {
  console.log(arguments);
  console.log(arguments.length);
};</pre>
<p>So what am I griping about?  Try doing <code>arguments.shift()</code>.  Uh-oh, looks like arguments.shift isn&#8217;t a function; but that&#8217;s a function of an Array.  Another bit of fun you can do is <code>console.log(arguments.constructor)</code>.  That will print to your console &#8220;Object()&#8221; while if you did <code>[].constructor</code>, that will print &#8220;Array()&#8221;.  Having fun yet?</p>
<p>This also isn&#8217;t just limited to <code>arguments</code>.  It seems that a lot of the DOM(document object model) collections are returned as these objects rather than arrays: <code>document.getElementsByTagName()</code>, <code>document.images</code>, <code>document.childNodes</code>.  In some cases, these array-not-arrays would be better suited to become arrays.</p>
<h3>Making the Array-like Objects become Arrays</h3>
<p>Well, that heading is a misnomer.  If we want those array-like objects to behave like arrays, we are going to need a new array.</p>
<pre class="ruby" title="code">var testFunction = function() {
  // Create a new array from the contents of arguments
  var args = Array.prototype.slice.call(arguments);

  var a = args.shift();
  console.log("The first argument is: %s", a);

  // send the remaining arguments to some other function
  someOtherFunction(args);
};</pre>
<p>Clearly, the magic is all in <code>Array.prototype.slice.call(arguments)</code>.  So let me break it down per piece.</p>
<dl>
<dt><code>Array</code></dt>
<dd>this is the name of the base object that we want</dd>
<dt><code>prototype</code></dt>
<dd>this can be thought of as the namespace for the instance methods of an array</dd>
<dt><code>slice</code></dt>
<dd>this extracts a section of an array and returns a new array, and without a beginning and ending index, it simply returns a copy of the array</dd>
<dt><code>call</code></dt>
<dd>this is a very useful function, it allows you to call a function from one object and use it in the context of another</dd>
</dl>
<p>Tada!  As a side note, if you are used to using <a href="http://www.prototypejs.org,">the prototype framework</a> then you can convert these array-like objects to arrays using <code>$A()</code>, even though Prototype does it&#8217;s array conversion differently.</p>
<p>Speaking of <code>$A</code>.  Let&#8217;s say you don&#8217;t like typing that long string code above and *you&#8217;re not using Prototype*.  Then you can create a shortcut just like the Prototype folks:</p>
<pre class="ruby" title="code">var $A = function(obj) {
  return Array.prototype.slice.call(obj);
};

// Example usage:
$A(document.getElementsByTagName("li"));</pre>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/06/28/array-like-objects-in-javascript/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>How to Create Objects in Object-Oriented JavaScript with Prototype</title>
		<link>http://shifteleven.com/articles/2007/04/29/how-to-create-objects-in-object-oriented-javascript-with-prototype?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-create-objects-in-object-oriented-javascript-with-prototype</link>
		<comments>http://shifteleven.com/articles/2007/04/29/how-to-create-objects-in-object-oriented-javascript-with-prototype#comments</comments>
		<pubDate>Sun, 29 Apr 2007 10:40:22 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[oop]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=28</guid>
		<description><![CDATA[Javascript Kata has a teriffic an article on how to create objects with JavaScript the old fashion way, without any JavaScript libraries. But I use prototype and it has its very own way to create a classes. Creating an empty &#8230; <a href="http://shifteleven.com/articles/2007/04/29/how-to-create-objects-in-object-oriented-javascript-with-prototype">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.javascriptkata.com">Javascript Kata</a> has a teriffic <a href="http://www.javascriptkata.com/2007/03/23/how-to-create-objects-in-object-oriented-javascript/">an article on how to create objects with JavaScript</a> the old fashion way, without any JavaScript libraries.  But I use <a href="http://www.prototypejs.org/">prototype</a> and it has its very own way to create a classes.</p>
<p><span id="more-28"></span></p>
<h3>Creating an empty class</h3>
<p>In keeping with the cat theme of Javascript Kata, I will create my own <code>Cat</code> class.  This is very easy to do; you simply create a new class and assign it to a variable.</p>
<pre class="javascript" title="code">  var Cat = Class.create();</pre>
<h3>Creating the constructor</h3>
<p>Unlike the Javascript Kata example, the constructor is not set inside of the function which created the class.  Instead it is put into the prototype attribute of the class, under the special method name <code>initialize</code>.</p>
<pre class="javascript" title="code">  var Cat = Class.create();
  Cat.prototype = {
    initialize: function(name) {
      this.name = name;
    }
  };</pre>
<h3>Adding a instance method</h3>
<p>To add an instance method to our <code>Cat</code> class, all one has to do is add another property to the prototype definition.</p>
<pre class="javascript" title="code">  var Cat = Class.create();
  Cat.prototype = {
    initialize: function(name) {
      this.name = name;
    },
    meow: function() {
      alert(this.name + " : meow!");
    }
  };</pre>
<p>What I like about this is it keeps all references to <code>this</code> in one spot.</p>
<h3>Making the cat meow</h3>
<p>The way that the code is constructed is different; however, the way to instantiate our Cat class is exactly the same as it would be if you didn&#8217;t use prototype.</p>
<pre class="javascript" title="code">  var mistigri = new Cat('Mistigri');
  mistigri.meow();</pre>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/04/29/how-to-create-objects-in-object-oriented-javascript-with-prototype/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Firebug and the Console API</title>
		<link>http://shifteleven.com/articles/2007/02/09/firebug-and-the-console-api?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=firebug-and-the-console-api</link>
		<comments>http://shifteleven.com/articles/2007/02/09/firebug-and-the-console-api#comments</comments>
		<pubDate>Fri, 09 Feb 2007 10:34:26 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[console]]></category>
		<category><![CDATA[firebug]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2007/02/09/firebug-and-the-console-api</guid>
		<description><![CDATA[Among the many Firefox extensions out there, there exists Firebug and it is good. It is truly an amazing piece of software. There is a CSS(cascading style sheets) viewer, so that when you inspect an element in the DOM(document object &#8230; <a href="http://shifteleven.com/articles/2007/02/09/firebug-and-the-console-api">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Among the many <a href="https://addons.mozilla.org/firefox/extensions/">Firefox extensions</a> out there, there exists <a href="http://www.getfirebug.com,">Firebug</a> and it is       good.  It is truly an amazing piece of software.  There is a CSS(cascading style sheets) viewer, so that when you inspect an element in the DOM(document object model), you can view all of the CSS attributes that apply to that element.  Not only does it show you the applicable CSS rules, it breaks it down to the styles being used and to the styles which have been overwritten.  Very nice.  There are many other things it does, but one feature in particular that I don&#8217;t think I  would want to live witout is the console API(application programming interface).</p>
<p><span id="more-26"></span></p>
<h3>Console API</h3>
<p><code>alert('performing mouseover')</code> or <code>alert(myvalue)</code> is the first approach I took in order to get input on what was going on in the midst of my code.  Then I    wised up a little and made an debugging area in the HTML(hypertext markup language) where I would send those messages .  Well Firebug kicks that up a notch     with the  <code>console</code> object.  You can call one of several types of messages to write messages to the Firebug console: <code>log()</code>, <code>info()</code>, <code>debug()</code>, <code>warn()</code>,    and <code>error()</code>.</p>
<pre class="javascript" title="code">function dummyFunction(number) {
  if((number % 2) == 0)
    console.debug('even');
  else
    console.debug('odd');

  try {
    var t = 1 / number;
  catch(e) {
    console.error(e.toString());
  }
}</pre>
<p>Now you have a way of getting feedback about what you are doing without resorting to the dreaded <code>alert()</code> statement.  The power doesn&#8217;t stop here. <code>console.   dir(myObj)</code> will print out a metric-pony load&#8217;s worth of information about an object in your console for you.  If the object has an attribute, this will let    you see what it is, and what values are stored in that attribute.  Absolutely fabulous when you&#8217;re not sure exactly what an object is, or what it does.</p>
<h3>Units Tests NOT Be Damned</h3>
<p>Along with writing messages to the Firebug console, you can also write tests.  By using <code>console.assert()</code>, and a slew of <a href="http://cheat.errtheblog.com/s/firebug/">other firebug assertions</a>, you can start gaining a level of confidence in the code you write.</p>
<p>I just noticed the assertions today, so I haven&#8217;t used any of this just yet.  I imaging that one would create an HTML file, separate from all other pages on    the site, and create the tests in there.  If someone has done any assertion files, I would love to know your approach and any tips you may have.</p>
<h3>The Best Thing of All</h3>
<p>What could make this even better than it is right now?  Well, the answer is <a href="http://www.getfirebug.com/lite.html.">Firebug lite</a> Without it, the downside to    using Firebug is that other browsers, like Safari, Opera, and Internet Explorer, won&#8217;t know what do to with those commands and will just blow up in your face.  Firebug lite adds that Console API functionality to the other browsers.  By default, the Firebug lite console window stays hidden until you activate it.  Once  activated, all of you messages will be available to you.  All the more reason to write assertions, since you can now check your code quickly against all of your browsers.</p>
<p>If you don&#8217;t have this extension and you do JavasSript programming, or any other HTML coding really, then you need to get it right away and discover the all the other awesome aspects of Firebug.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2007/02/09/firebug-and-the-console-api/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Mimicking the :hover Pseudo-class in IE</title>
		<link>http://shifteleven.com/articles/2006/12/14/mimicking-the-hover-pseudo-class-in-ie?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mimicking-the-hover-pseudo-class-in-ie</link>
		<comments>http://shifteleven.com/articles/2006/12/14/mimicking-the-hover-pseudo-class-in-ie#comments</comments>
		<pubDate>Thu, 14 Dec 2006 21:30:37 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[HTML & CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[IE]]></category>
		<category><![CDATA[prototype]]></category>
		<category><![CDATA[pseudo-class]]></category>
		<category><![CDATA[suckerfish]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/?p=21</guid>
		<description><![CDATA[Internet Explorer frustrates the living hell out of me. Event though IE 7 is finally out, it doesn&#8217;t mean that IE 6 can be ignored. I really look forward to the day when my CSS(cascading style sheet) files aren&#8217;t full &#8230; <a href="http://shifteleven.com/articles/2006/12/14/mimicking-the-hover-pseudo-class-in-ie">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.ie7.com/">Internet Explorer</a> frustrates the living hell out of me.  Event though IE 7 is finally out, it doesn&#8217;t mean that IE 6 can be ignored.  I really look forward to the day when my CSS(cascading style sheet) files aren&#8217;t full of unnecessary classes and hacks because the major browser vendors got it right and because everyone has casted away the garbage.  Until then, I am still in search of tricks to simplifying my life.</p>
<p>One of these tricks is to make IE pretend like it knows how to use the <code>:hover</code> pseudo-class on all tags.</p>
<p>If you have ever tried to do a <a href="http://alistapart.com/articles/dropdowns/,">suckerfish dropdown</a> then you have gone through the same thing:  excitement as you have learned how to use structural markup to create a dropdown and then frustration as your work has been nullified by IE.  The fix involves creating duplicate <a href="http://css.maxdesign.com.au/selectutorial/">selectors</a> of those using <code>:hover</code>, but instead of using <code>:hover</code>, replace it with a class name <code>.hover</code>.  Making what are essentially duplicates and managing more content doesn&#8217;t sit well with me.  The other trick to getting suckerfish to work in IE is to use JavaScript.  The script will add a class definition to the tag when a user&#8217;s mouse if over the element and then removes the class when the users mouse is no longer over it.  Since this method uses JavaScript to solve one problem, why not make it solve both?</p>
<p><span id="more-21"></span></p>
<h3>The Code</h3>
<p>There is a requirement to using this code and that is you will need <a href="http://prototype.conio.net/.">prototype 1.5</a></p>
<pre class="javascript" title="code">var HoverBehavior = Class.create();
HoverBehavior.prototype = {
  initialize: function() {
    $A(document.styleSheets).each( function(stylesheet) {
      $A(stylesheet.rules).each( function(rule) {
        if( rule.selectorText.match(/:hover/i) ) {
          stylesheet.addRule( rule.selectorText.replace(/:hover/ig, '.hover'), rule.style.cssText );
        }
      });
    });

    $A(arguments).each( function(arg) {
      $$(arg).each( function(tag) {
        Event.observe(tag, 'mouseover', function() { Element.addClassName(tag, 'hover'); });
        Event.observe(tag, 'mouseout', function() { Element.removeClassName(tag, 'hover'); });
      });
    });
  }
};</pre>
<p>In summary, it loops through all of the <a href="http://www.javascriptkit.com/domref/stylesheet.shtml,">stylesheets</a> and for each stylesheet, it loops through all of the rules.  The first part of the initialization will only work in IE.  When looping through the rules, IE uses the <code>rules</code> attribute while others use <code>cssRules</code>.  Since this is only meant for IE, I am not going to bother making it cross-browser.</p>
<p>While looping through all of the rules, it is checking the selector text to see if <code>:hover</code> is in that text.  If so it will append a new CSS rule to the stylesheet.  The selector text for that rule is just like text of the matched selector; however, all instances of <code>:hover</code> have been replaced with <code>.hover</code>.  The new rule&#8217;s style is simply a copy of the matched selector.</p>
<p>That covers part 1 of the suckerfish fix, part 2 is to add the mouseover, mouseout states to the tags using <code>:hover</code>.</p>
<h3>Usage</h3>
<p><strong>After the page has been loaded</strong>, then it is time to create a new instance of the HoverBehavior class.  Since this is only for IE, it would be wise to use <a href="http://www.javascriptkit.com/howto/cc2.shtml">IE conditionals</a> as that your other users, who are using complaint browsers, shouldn&#8217;t have to process any unnecessary code.</p>
<pre class="html" title="code">&lt;!--[if lt IE 7]&gt;
&lt;script type="text/javascript" charset="utf-8"&gt;
//&lt;![CDATA[
  new HoverBehavior('li');
//]]&gt;
&lt;/script&gt;
&lt;![endif]--&gt;</pre>
<p>The constructor can take any number of arguments that you would give to prototype&#8217;s <code>$$</code> function, which are like CSS selectors themselves.  I could have also done something like:</p>
<ul>
<li> <code>new HoverBehavior('#nav li', '#footer li');</code></li>
<li><code>new HoverBehavior('li', 'p', 'span');</code></li>
<li> <code>new HoverBehavior('*');</code></li>
</ul>
<p>The reason I don&#8217;t assume the last one in that list is because I don&#8217;t want to kill the user&#8217;s browser.  Instead of being lazy and choosing all of the elements, I only want to put the <code>mouseover</code>, <code>mouseout</code> functionality on the elements that need it.</p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/12/14/mimicking-the-hover-pseudo-class-in-ie/feed</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Engrish Javascript</title>
		<link>http://shifteleven.com/articles/2006/10/20/engrish-javascript?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=engrish-javascript</link>
		<comments>http://shifteleven.com/articles/2006/10/20/engrish-javascript#comments</comments>
		<pubDate>Sat, 21 Oct 2006 02:08:22 +0000</pubDate>
		<dc:creator>K. Adam Christensen</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[engrish]]></category>
		<category><![CDATA[Kim Jong Il]]></category>
		<category><![CDATA[racism]]></category>
		<category><![CDATA[recursion]]></category>
		<category><![CDATA[Team America]]></category>

		<guid isPermaLink="false">http://dev.fecalrod.com/articles/2006/10/20/engrish-javascript</guid>
		<description><![CDATA[In what I can think of as the most important JavaScript that I have ever written, I have made something which will parse the DOM(Document Object Model) and replace all of the &#8216;l&#8217;s with &#8216;r&#8217;s. This idea came about after &#8230; <a href="http://shifteleven.com/articles/2006/10/20/engrish-javascript">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In what I can think of as the most important JavaScript that I have ever written, I have made something which will parse the DOM(Document Object Model) and replace all of the &#8216;l&#8217;s with &#8216;r&#8217;s.  This idea came about after watching <a href="http://www.rottentomatoes.com/m/team_america_world_police/">Team America: World Police</a> about 1,000 times and after <a href="http://en.wikipedia.org/wiki/Kim_Jong-il">Kim Jong Il</a> gave his <a href="http://www.theage.com.au/news/World/Kim-Jongil-sorry-about-nuclear-test/2006/10/20/1160851096275.html">apology</a> for doing some nuke testing. Back to the script:</p>
<pre class="javascript" title="code">function engrish(n) {
	if(n.nodeType == document.TEXT_NODE) {
		n.nodeValue = n.nodeValue.replace(/l/g, 'r').replace(/L/g, 'R');
	} else if(n.hasChildNodes()) {
		for(var i=0; i&lt;n.childNodes.length; i++) {
			engrish(n.childNodes[i]);
		}
	}
}</pre>
<p>To execute this code, simply call <code>engrish(document.documentElement);</code>.  Using <a href="http://www.htmlgoodies.com/primers/jsp/article.php/3622321,">recursion</a> this function goes through the DOM, finds text nodes and replaces the characters.</p>
<p><span id="more-16"></span></p>
<p>This is fine an dandy if you put this on your site so you can quickly convert your copy to <a href="http://www.engrish.com/detail.php?imagename=biohazard.jpg&amp;category=Signs/Posters&amp;date=2003-10-16;">engrish</a> however there is something that you can do to turn any page into it&#8217;s <a href="http://www.engrish.com/detail.php?imagename=dewdew.jpg&amp;category=Candy&amp;date=1996-10-18">engrish</a> form.  You can save this code as a <a href="http://mozilla.gunnars.net/firefox_bookmarks_tutorial.html.">bookmark</a></p>
<p>If you would like an example of what the bookmark URL would be, just <a href="javascript:function engrish(n) {if(n.nodeType == document.TEXT_NODE) {n.nodeValue = n.nodeValue.replace(/l/g, 'r').replace(/L/g, 'R');} else if(n.hasChildNodes()) {for(var i=0; i&lt;n.childNodes.length; i++) {engrish(n.childNodes[i]);}}} engrish(document.documentElement);">engrish-ify</a> this page and save the link as a bookmark (you can drag that link into your bookmark toolbar in <a href="http://www.mozilla.com/firefox/)">Firefox</a></p>
]]></content:encoded>
			<wfw:commentRss>http://shifteleven.com/articles/2006/10/20/engrish-javascript/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

