<?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>TimKadlec.com &#187; Javascript</title>
	<atom:link href="http://timkadlec.com/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://timkadlec.com</link>
	<description>A Wisconsin based web developer writing about the web.</description>
	<lastBuildDate>Tue, 13 Jul 2010 01:30:40 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Exploring Cross Document Communication</title>
		<link>http://timkadlec.com/2008/12/exploring-cross-document-communication/</link>
		<comments>http://timkadlec.com/2008/12/exploring-cross-document-communication/#comments</comments>
		<pubDate>Wed, 17 Dec 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/exploring-cross-document-communication/</guid>
		<description><![CDATA[One of the new features that HTML5 offers web developers is a way to send information between documents on different sites via Javascript without sacrificing security.]]></description>
			<content:encoded><![CDATA[<p>One of the new features that HTML5 offers web developers is a way to send information between documents on different sites via Javascript. Currently for security and privacy reasons, browsers prevent cross site scripting but with HTML5&#8242;s Cross Document Messaging, the intention is to allow documents to communicate with each other without sacrificing security.</p>
<p>To experiment with these methods and events, you&#8217;ll need to be running either IE8, Firefox 3 or the WebKit Nightlies. Opera 9+ provides support as well, but they use an older version of the spec which required the postMessage method to be called from the document object instead of the window object.</p>
<p>There are two key steps involved with HTML5 Cross Document Messaging. The first is posting the message. You do this by calling the window&#8217;s postMessage() function. The postMessage function takes two arguments: the message to be sent, and the target origin.</p>
<p>Then, to receive the message in the other window, you need to watch for the window&#8217;s message event using window.addEventListener or something similar. To help show how this works, I&#8217;ve set up an example for you to see <a href="http://www.timkadlec.com/crosssite_get.asp">here</a>. In my example, both the sending window and the receiving window are located within the same domain (timkadlec.com), but as long as you have a reference to a window, you can communicate cross domain the same way.</p>
<h2>Walking the Code</h2>
<p>Take a look at the source code and you&#8217;ll see that I&#8217;m simply using one window (window A) to open the other (window B) so that I have a reference to it. Window B contains two buttons that when clicked, use the postMessage method to post a message back to window A, like so:</p>
<ul class="code">
<li>window.opener.postMessage(&#8216;John Smith&#8217;, &#8216;http://www.timkadlec.com&#8217;);</li>
</ul>
<p>We use window.opener to get our reference to window a, and then call the postMessage function and send the message &#8216;John Smith&#8217; back to it. We specify that the origin is timkadlec.com in the targetOrigin argument.</p>
<p>Now back in window A, we need to prepare to receive the message. To do so, we look for the message event.</p>
<ul class="code">
<li>window.addEventListener(&#8216;message&#8217;, receiver, false);</li>
</ul>
<p>As you can see above, I&#8217;m using addEventListener to listen for the message event, and once the event occurs, we call the receiver function.</p>
<ol class="code">
<li>function receiver(e){</li>
<li class="tab1">if (e.origin == &#8216;http://www.timkadlec.com&#8217;) {</li>
<li class="tab2">if (e.data == &#8216;John Smith&#8217;) {</li>
<li class="tab3">alert(e.data);</li>
<li class="tab3">e.source.postMessage(&#8216;Valid User&#8217;, e.origin);</li>
<li class="tab2">} else {</li>
<li class="tab3">alert(e.data);</li>
<li class="tab3">e.source.postMessage(&#8216;FAIL&#8217;, e.origin);</li>
<li class="tab2">}</li>
<li class="tab1">}</li>
<li>}</li>
</ol>
<p>In the receiver function, we verify that the origin of the event is timkadlec.com (line 2). This is highly encouraged, as it ensures that we only receive messages from domains we are expecting to hear from. If you skipped this step, any domain could freely affect your page, and that could get a bit messy.</p>
<p>Then, we use the event&#8217;s data property to retrieve the message that was sent. Based on the message received, we then use the source property of the event to obtain a reference to the window that sent the message. Then, again using the postMessage method (lines 5 and 8), we send a message back to window A.</p>
<p>This is a pretty straightforward example, and is really just meant to demonstrate how easy it is to post messages back and forth between documents. There&#8217;s another good example up that <a href="http://austinchau.blogspot.com/2008/11/html5-cross-document-messaging.html">makes use of iframes</a> if you want to see another example of cross document messaging.</p>
<h2>Some Security Considerations</h2>
<p>Hopefully you can see that cross document messaging is both simple, and potentially quite useful for things like widgets, or authentication. However, there are some security risks if you don&#8217;t take the time to double check a few things. First, like mentioned before, you should always double check the origin of the sent message. You don&#8217;t want to be just accepting messages from anyone&#8230;that&#8217;s kind of the reason cross-site scripting isn&#8217;t allowed in the first place.</p>
<p>Secondly, it is possible to use the asterisk in the targetOrigin argument to allow your message to be posted to any domain. However, you should be sure to never use the asterisk symbol when sending confidential information. In those cases, you should be specifying the targetOrigin specifically so that you can guarantee that only the intended recipient gets the information.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/12/exploring-cross-document-communication/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Canvas Element: Starting to Draw</title>
		<link>http://timkadlec.com/2008/09/the-canvas-element-starting-to-draw/</link>
		<comments>http://timkadlec.com/2008/09/the-canvas-element-starting-to-draw/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[(x)html]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/the-canvas-element-starting-to-draw/</guid>
		<description><![CDATA[Last time around, we took a general look at the canvas element and how it is supported (or not) in various browsers. This time, we'll start to go into the element in a bit more detail and start to look at some the things we can do with it.]]></description>
			<content:encoded><![CDATA[<p>Last <a href="post.asp?q=73">time around</a>, we took a general look at the canvas element and how it is supported (or not) in various browsers. This time, we&#8217;ll start to go into the element in a bit more detail and start to look at some the things we can do with it.</p>
<h2>A Quick Look at Attributes</h2>
<p>We&#8217;ve already seen how to set up the canvas element in HTML:</p>
<p>You&#8217;ve probably noticed that we&#8217;ve included an id attribute on our canvas element to make it easier for us to access the element in our Javascript. You can also apply other standard attributes like class, title or tabindex. Two other attributes, height and width, will also be used fairly regularly.</p>
<p>You can define the height and width as attributes in the canvas element, or you can use CSS to define the dimensions of your element. If you use CSS, however, your canvas will scale to meet the dimensions you define instead of simply resizing the area. Neither height nor width are necessary, however. If you choose to not define the size of the canvas element, then it defaults to a size of 300 pixels wide by 150 pixels high.</p>
<h2>Roll Up Your Sleeves&#8230;</h2>
<p>All of this so far has been pretty easy&#8230;but also boring. The canvas element&#8217;s real power, of course, is the ability to use Javascript to manipulate it. To do so, we have to get a rendering context using the getContext() function. The rendering context is what allows us to actually manipulate the content in the canvas element. The function is straight forward and easy to use:</p>
<ol class="code">
<li>var canvas = document.getElementById(&#8216;canvas&#8217;);</li>
<li>var context = canvas.getContext(&#8217;2d&#8217;);</li>
</ol>
<p>Currently, &#8220;2d&#8221; is the only defined context that we can obtain. In the future, it is not unreasonable to expect to see that expand and include support for a three dimensional drawing context. Of course in a real-world setting you&#8217;ll want to check to make sure the browser supports the getContext method in the first place. The canvas element is still relatively new and there will be a fair amount of browsers that will not support it.</p>
<h2>The One and Only</h2>
<p>Now that we have a rendering context, let&#8217;s make use of it by starting to draw something to the canvas. The canvas element only natively supports one shape and that is the rectangle. Don&#8217;t panic&#8230;.you&#8217;ll see later that there are plenty of methods available for us to create everything from a basic circle to very complex abstract shapes.</p>
<p>For now though, we&#8217;ll keep it simple and just make a rectangle. We have three functions that are available to use for this: fillRect(), strokeRect(), and clearRect(). The functions do pretty much exactly what you would think based on their names. fillRect() draws a filled rectangle; strokeRect() draws a rectangle with border, or stroke, around it; and clearRect() clears the area and makes a fully transparent rectangle. To make it even more simple, each of the functions takes the exact same parameters. Let&#8217;s take for example the following line of code:</p>
<ul class="code">
<li>context.fillRect(0,0,50,75);</li>
</ul>
<p>As you can see, the function takes four parameters. The first two define the starting point of the shape, the x and y coordinates. Thankfully the coordinates follow common sense. The origin or (0,0) is the top left of the canvas element. So (0,10) would be at the top and 10 pixels from the left.</p>
<p>The next two parameters are the width and height of the canvas element. In this case, I made a rectangle that is 50 pixels wide and 75 pixels high. So the result of the above line of code is a 50 pixel by 75 pixel, filled rectangle in the top left corner of the canvas element. To get a good idea of the results of each of the rectangle functions, we&#8217;ll use the following code (we&#8217;ve also set the height and width attributes on our canvas element to 125 pixels each) :</p>
<ol class="code">
<li>context.fillRect(0,0,50,50);</li>
<li>context.clearRect(25,25,50,50);</li>
<li>context.fillRect(50,50,50,50);</li>
<li>context.strokeRect(75,75,50,50);</li>
</ol>
<p>The result, <a href="canvas.asp">as you can see here</a>, is four overlapping rectangles. Remember, you&#8217;ll need Firefox (1.5+), Safari, or Opera (9+) to view it. As you can see, the clear rectangle clears out the area it covers. The stroke rectangle, on the other hand, doesn&#8217;t clear out the area, so you can see the filled rectangle through it.</p>
<h2>Next Time</h2>
<p>Next time around, we&#8217;ll start to look at some of the other functions available, and how we can use those functions to start making a variety of shapes&#8230;not just simple rectangles. To wet your appetite a bit in the meantime, have a look at <a href="http://blog.nihilogic.dk/2008/09/sandbag-text-wrapping-with-canvas.html">another great example</a> of how the canvas element can be used.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/09/the-canvas-element-starting-to-draw/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with the Canvas Element</title>
		<link>http://timkadlec.com/2008/09/getting-started-with-the-canvas-element/</link>
		<comments>http://timkadlec.com/2008/09/getting-started-with-the-canvas-element/#comments</comments>
		<pubDate>Thu, 11 Sep 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[(x)html]]></category>
		<category><![CDATA[html5]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/getting-started-with-the-canvas-element/</guid>
		<description><![CDATA[There's a lot of really exciting and interesting features arriving just around the corner in the world of web development. One of the new features that is receiving a lot of attention, and for good reason, is the new canvas element.]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a lot of really exciting and interesting features arriving just around the corner in the world of web development. One of the new features that is receiving a lot of attention, and for good reason, is the new canvas element. The canvas element offers a lot of power to web developers, but can take a bit for some people to get comfortable with. So, I&#8217;m going to run a series of posts introducing this powerful new feature, and showing some of the ways it can be utilized.</p>
<h2>What Is It, and Who Supports It?</h2>
<p>The canvas element was originally implemented in Safari, and then became standardized in the HTML5 specification. The element allows developers to dynamically draw onto a blank &#8216;canvas&#8217; in a website. Thankfully, you don&#8217;t have to wait to play around with this element. Currently, you can find support for it in Firefox (version 1.5 and newer), Safari, or Opera (version 9 and newer). In addition, you can twist IE&#8217;s arm a bit thanks to Google and Mozilla. Google has created <a href="http://excanvas.sourceforge.net/">ExplorerCanvas</a>, a script that allows your canvas scripts to work in IE. For more intensive applications, Mozilla created has created an <a href="http://arstechnica.com/news.ars/post/20080819-mozilla-drags-ie-into-the-future-with-canvas-element-plugin.html">ActiveX plugin</a> for IE to bring canvas support to the widely used browser. So, there&#8217;s little reason why you can&#8217;t start using it today&#8230;.Google Maps does!</p>
<p>Unfortunately, there is some discrepancy in the way browsers support the canvas element right now. For example, in Safari, the canvas tag works a lot like the img tag&#8230;it doesn&#8217;t require a closing tag. In Safari, you can close the element like so:</p>
<ul class="code"></ul>
<p>In Firefox, however, the canvas element requires a closing tag:</p>
<ul class="code"></ul>
<p>The problem comes in with alternate content. In Firefox, we can simply throw our alternate content in between the opening and closing canvas tags. If the browser doesn&#8217;t support the canvas element, then the alternate content displays. In Safari, the content displays regardless. There are a few ways you can hack around this however, including this one presented by <a href="http://mattsnider.com/languages/javascript/intro-to-html-canvas-tag/">Matt Snider</a>.</p>
<h2>Why It&#8217;s Cool</h2>
<p>The canvas element is not meant for static images&#8230;though it can certainly be used to do that. The real power of it comes when we make use of Javascript to manipulate the canvas element and create dynamic visualizations like data charts and graphs, interactive diagrams and games. In fact, there are a couple impressive Javascript game recreations that have already been developed that make use of the canvas element. You can already play <a href="http://www.nihilogic.dk/labs/mariokart/">Mario Kart</a>, <a href="http://blog.nihilogic.dk/2008/04/super-mario-in-14kb-javascript.html">Super Mario</a>, and an incredibly addicting game called <a href="http://www.gamesforthebrain.com/game/oooze/">Ooze</a>.</p>
<p>The canvas element is a great example of where implementation precedes standardization. Safari implemented it, then Firefox and Opera caught on, and now the <abbr title="Web Hypertext Application Technology Working Group">WHAT-WG</abbr> is incorporating it into the HTML5 specification. Once implemented, it provides us with a standardized, cross-browser means to dynamically display data and react to user events in a way that previously required Flash.</p>
<h2>What&#8217;s Coming Up</h2>
<p>Next time around, we&#8217;ll start to look at the canvas element in more detail including the attributes available. We&#8217;ll also start diving into some Javascript and some of the methods provided by the DOM to interact with the canvas element.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/09/getting-started-with-the-canvas-element/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Living In Harmony</title>
		<link>http://timkadlec.com/2008/08/living-in-harmony/</link>
		<comments>http://timkadlec.com/2008/08/living-in-harmony/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/living-in-harmony/</guid>
		<description><![CDATA[The big news in the Javascript community for the last week has been the announcement of ECMAScript Harmony. A lot of news is really just overblown, but this is a big development, and one that any Javascript developer should be following.]]></description>
			<content:encoded><![CDATA[<p>The big news in the Javascript community for the last week has been the announcement of ECMAScript Harmony. A lot of news is really just overblown, but this is a big development, and one that any Javascript developer should be following.</p>
<h2>Some Background</h2>
<p>There&#8217;s been a lot of talk in the Javascript community over the past 9 years or so about the development of ECMAScript 4, what was to be the foundation for what was being called Javascript 2. It was a controversial and fairly dramatic change from ECMAScript 3 (Javascript). There was going to be support for classes, inheritance, type annotations, namespaces&#8230;the whole flavor of the language was going to dramatically change.</p>
<p>ECMAScript 4 was being developed primarily by Adobe, Mozilla, Opera and Google and was primarily based on the features those organizations wished to implement. Others, including Microsoft and Yahoo, found the proposed changes in ES4 to be to dramatic, and instead wanted to implement minor changes and bug fixes to ES3, labeling it ES3.1 instead.</p>
<h2>What Happened?</h2>
<p>Obviously with division among such major organizations, something was going to have to give. So, at a recent TC39 meeting (the committee in charge of developing the ECMAScript standard) met and a resolution was met. The two sides would merge their ideas together with a new committed focus to ensuring simplicity in the new changes to the language&#8230;enter ECMAScript Harmony. In an email, Brendan Eich of Mozilla laid down the 4 primary goals of ECMAScript Harmony:</p>
<ol class="reg">
<li>Focus work on ES3.1 with full collaboration of all parties, and target two interoperable implementations by early next year.</li>
<li>Collaborate on the next step beyond ES3.1, which will include syntactic extensions but which will be more modest than ES4 in both semantic and syntactic innovation.</li>
<li>Some ES4 proposals have been deemed unsound for the Web, and are off the table for good: packages, namespaces and early binding. This conclusion is key to Harmony.</li>
<li>Other goals and ideas from ES4 are being rephrased to keep consensus in the committee; these include a notion of classes based on existing ES3 concepts combined with proposed ES3.1 extensions.</li>
</ol>
<h2>What Does It Mean?</h2>
<p>Well, for one, it means that the series of posts I had started on Javascript 2.0 are now completely worthless&#8230;and no&#8230;I will not reimburse you for the time spent reading them.</p>
<p>But far more importantly, it means that progress should speed up immensely. (There are ES4 proposals from 1999.) The plan appears to be to implement certain de facto standards rather quickly. For example, getters and setters are already implemented in each of the major browsers except for IE, and they will be thrown into the ES Harmony specification. (Which, by the way, brings up the interesting situation where implementation precedes specification, something that occurs often on the web and something you&#8217;ll probably see me talk more about in the future.)</p>
<p>Meanwhile, ActionScript 3.0 was already built to reflect the ECMAScript 4 proposed specifications&#8230;so it would appear they&#8217;re kind of left a bit high and dry. It sounds as though they are definitely committed to keeping in line with specifications, and that they plan on implementing new features laid out in the newly developed specification. They are also going to continue to keep their current features, like classes and type annotations, available in their language&#8230;think of it as an extension to the ECMAScript standard.</p>
<h2>My Thoughts</h2>
<p>All in all, I think the outcome is positive. ES4 had been taking forever to get going, and ES3.1 hadn&#8217;t been sounding like it would do much besides fix bugs. Now, we&#8217;ll have a new implementation soon and while it won&#8217;t have the same dramatic changes ES4 had in mind, there will be some interesting new features being added.</p>
<p>While I would&#8217;ve enjoyed some of the new features, Javascript gets to maintain a lot of flexibility here. ES4 would&#8217;ve tightened that up a bit, and I still haven&#8217;t really made up my mind on whether that would&#8217;ve been a good thing or not.</p>
<p>It&#8217;s also quite encouraging to see so many major players working together. Microsoft, Yahoo, Google, Mozilla, Opera and Adobe all working together in harmony. (I apologize for the pun&#8230;it was just there, and I decided to go with it.) One can only imagine having these organizations working together will ensure a high quality specification, and also lead to faster implementation of the spec.</p>
<h2>Around the Web</h2>
<p>This is certainly a huge development, and there has been no shortage of postings about it. There&#8217;s a lot of high quality discussion going on by some major players in the world of Javascript and ActionScript, and I highly recommend checking them out.</p>
<ul class="reg">
<li><a href="https://mail.mozilla.org/pipermail/es-discuss/2008-August/003400.html">Bredan Eich&#8217;s Original Email</a></li>
<li><a href="http://ejohn.org/blog/ecmascript-harmony/">John Resig: ECMAScript Harmony</a></li>
<li><a href="http://www.mikechambers.com/blog/2008/08/14/actionscript-3-and-ecmascript-4/">Mike Chambers: ActionScript 3 and ECMAScript 4</a></li>
<li><a href="http://yuiblog.com/blog/2008/08/14/premature-standardization/">Douglas Crockford: The Only Thing We Have To Fear Is Premature Standardization</a></li>
<li><a href="http://alex.dojotoolkit.org/2008/08/thoughts-on-harmony/">Alex Russell: Thoughts on Harmony</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/08/living-in-harmony/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>An Objective Look at Javascript 2.0: Strong Typing</title>
		<link>http://timkadlec.com/2008/04/an-objective-look-at-javascript-2-0-strong-typing/</link>
		<comments>http://timkadlec.com/2008/04/an-objective-look-at-javascript-2-0-strong-typing/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/an-objective-look-at-javascript-2-0-strong-typing/</guid>
		<description><![CDATA[In our first look at the new features of Javascript 2.0, we will focus on the new typing system. We are just going to highlight some of the major changes and potential uses]]></description>
			<content:encoded><![CDATA[<p>In our first look at the new features of Javascript 2.0, we will focus on the new typing system. We are just going to highlight some of the major changes and potential uses. For a more detailed look, take a look at the <a href="http://www.ecmascript.org/es4/spec/overview.pdf" target="_blank">ECMAScript 4.0 Language Overview</a>.</p>
<p>Traditionally, Javascript is a loosely-typed language, meaning that variables are declared without a type. For example:</p>
<p><code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>var a = 42; // Number declaration</li>
<li>var b = "forty-two"; // String declaration</li>
</ol>
<p></code></p>
<p>Since Javascript is loosely typed, we can get away with simple &#8216;var&#8217; declarations&#8230;the language will determine which data type should be used. In contrast, Javascript 2.0 will be strongly typed, meaning that type declarations will be enforced. The syntax for applying a given type will be a colon (:) followed by the type expression. Type annotation can be added to properties, function parameters, functions (and by doing so declaring the return value type), variables, or object or array initializers. For example:</p>
<p><code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>var a:int = 42; //variable a has a type of int</li>
<li>var b:String = "forty-two"; //variable b has a type of String</li>
<li></li>
<li>function (a:int, b:string)//the function accepts two parameters, one of type int, one of type string</li>
<li></li>
<li>function(...):int //the function returns a value with a type of int</li>
</ol>
<p></code></p>
<p>NOTE: There has been some confusion about enforcing type declarations so I thought I&#8217;d try to clear it up. Enforcing type declarations simply means that if you define a type, it will be enforced. You can choose to not define a type, in which case the variable or property defaults to a type of &#8216;Object&#8217; which is the root of the type heirarchy.</p>
<h2>Type Coercion</h2>
<p>Being a strongly typed system, Javascript 2.0 will be much less permissive with type coercion. Currently, the following checks both return true:</p>
<p><code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>"42" == 42</li>
<li>42 == "42"</li>
</ol>
<p></code></p>
<p>In both cases, the language performs type coercion&#8230;Javascript automatically makes them the same type before performing the check. In Javascript 2.0, both of those statements will resolve to a &#8216;false&#8217; value instead. We can still perform comparisons like those above; we just need to explicitly convert the data type using type casting. To perform the checks above and have them both resolve to &#8216;true&#8217;, you would have to do the following:</p>
<p><code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>int("42") == 42</li>
<li>string(42) == "42"</li>
</ol>
<p></code></p>
<p>While adding a strongly typed system does make the language a bit more rigid, there are some benefits to this change, particularly for applications or libraries that may be worked with elsewhere. For example, for a given method, we can specify what kinds of objects it can be a method for using the special &#8216;this&#8217; annotation. I&#8217;m sure there are many of you who just re-read that sentence and are scratching your heads trying to figure out what the heck that meant. An example may help:</p>
<p><code><br />
</code></p>
<p><code></p>
<ul class="code">
<li>function testing(this:myObject, a:int, b:string):boolean</li>
</ul>
<p></code></p>
<p>The method above accepts two arguments, an int and a string. The first part of the parameters (this:myObject) uses the this: annotation to state that the function can only be a method of objects that have the type of &#8216;myObject&#8217;. This way if someone else is using code we have created, we can restrict which objects they can use that method on, preventing it&#8217;s misuse and potential confusion.</p>
<h2>Union Types</h2>
<p>We can also use union types to add a bit of flexibility. Union types are collections of types that can be applied to a given property. There are four predefined union types in Javascript 2.0:</p>
<p><code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>type AnyString = (string, String)</li>
<li>type AnyBoolean = (boolean, Boolean)</li>
<li>type AnyNumber = (byte, int, uint, decimal, double, Number)</li>
<li>type FloatNumber = (double, decimal)</li>
</ol>
<p></code></p>
<p>In addition, we can set up our own union types based on what we need for a particular property:</p>
<p><code><br />
</code></p>
<p><code></p>
<ul class="code">
<li>type MySpecialProperty = (byte, int, boolean, string)</li>
</ul>
<p></code></p>
<p>One final thing I would like to mention is that in contrast to Java and C++, Javascript 2.0 is a dynamically typed system, not statically typed. In a statically typed system, the compiler verifies that type errors cannot occur at run-time. Statically typing would catch a lot of potential programming errors, but it also severely alters the way Javascript can be used, and would make the language that much more rigid. Because JS 2.0 is dynamically typed, only the run-time value of a variable matters.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/04/an-objective-look-at-javascript-2-0-strong-typing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>An Objective Look at Javascript 2.0: Looking Back</title>
		<link>http://timkadlec.com/2008/04/an-objective-look-at-javascript-2-0-looking-back/</link>
		<comments>http://timkadlec.com/2008/04/an-objective-look-at-javascript-2-0-looking-back/#comments</comments>
		<pubDate>Wed, 23 Apr 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/an-objective-look-at-javascript-2-0-looking-back/</guid>
		<description><![CDATA[There has been no shortage of debate over Javascript 2.0, based on ECMAScript 4.0. Some people are extremely excited about some of the new features being discussed, and some feel that Javascript 2.0 is shaping up to look a bit too much like Java or even C++ for their tastes.]]></description>
			<content:encoded><![CDATA[<p>There has been <a href="http://www.dustindiaz.com/java-in-our-script/" target="_blank">no</a> <a href="http://blogs.msdn.com/cwilso/archive/2007/10/31/what-i-think-about-es4.aspx" target="_blank">shortage</a> <a href="http://weblogs.mozillazine.org/roadmap/archives/2007/10/open_letter_to_chris_wilson.html" target="_blank">of</a> <a href="http://my.opera.com/haavard/blog/2007/11/02/ars-technica-mozilla-the-bad-guys-fighting-microsoft-the-good-guys" target="_blank">debate</a> over Javascript 2.0, based on ECMAScript 4.0. Some people are extremely excited about some of the new features being discussed, and some feel that Javascript 2.0 is shaping up to look a bit too much like Java or even C++ for their tastes.</p>
<p>Whether you like the new features being proposed, think they&#8217;re silly and unnecessary, or have no idea what the heck I am talking about, I think it&#8217;s important to have a firm grasp on some of the changes being proposed. Doing so will help you to better understand both sides of the debate, and also help to prepare you for when Javascript 2.0 becomes available for use.</p>
<p>There&#8217;s far too many changes and fixes to discuss them in one post, so this will be an ongoing serious of posts. I&#8217;ll be taking a look at what the new language provides us and why. Hopefully by taking a closer look at all the changes, we can get a better feel for how those changes affect both web developers and javascript in general. First though, we should take a quick look at how Javascript got to this point, and the reasoning behind the changes beings suggested in Javascript 2.0.</p>
<h2>Once Upon a Time&#8230;</h2>
<p>Javascript has been around since 1995, when it was debuted in Netscape Navigator 2.0. The original intent was for Javascript to provide a more accessible way for web designers and non-Java programmers to utilize Java applets. In reality though, Javascript was used far more often to provide levels of interactivity on a page&#8230;allowing for the manipulation of images and document contents.</p>
<p>Microsoft then implemented Javascript in IE 3.0, but their implementation varied from that of Netscape�s and it became apparent that some sort of standardization was necessary. So the European Computer Manufacturers Association (ECMA) standards organization developed the TC39 committee to do just that.</p>
<p>In 1997, the first ECMA standard, ECMA-262, was adopted. The second version came along a bit later and consisted primarily of fixes. In December of 1999, when the third version rolled out, the changes were more drastic. New features like regular expressions, closures, arrays and object literals, exceptions and do-while statements were introduced, greatly adding value to the language. This revision, ECMAScript Edition 3, is fully implemented by Javascript 1.5, which is the most recently released version of Javascript.</p>
<p>Like ECMAScript 3, the proposed ECMAScript 4 specification will provide a very noticeable change in the language. As it stands now, Javascript 2.0 will be featuring, among other changes, support for things like scoping, typing and class support.</p>
<h2>Let the Debate Begin</h2>
<p>While some of the changes are bug fixes, the justification for the major revisions appears to be largely based on providing better support for developing larger-scale applications. With the growing popularity of <abbr title="Asynchronous Javascript and XML">AJAX</abbr>, and the rise of <abbr title="Rich Internet Applications">RIAs</abbr>, Javascript is now being used for much larger-scale apps than it was ever intended for. The proposed changes to ECMAScript 4 are intended to help make development of those kinds of apps easier by making the language more disciplined and therefore making it easier for multiple developers to work on the same application.</p>
<p>This is where the debate starts&#8230;.how much do we need these revisions? Technically, we can implement a lot of the same kinds of structures using the language as it stands currently. The proposed changes are aimed at making that easier, but there are some people who worry about the effect this may have on what is currently a very expressive and lightweight language.</p>
<p>Which group is correct? Are the changes going to make our lives as Javascript developers easier, or force us to lose a lot of what makes Javascript such an attractive scripting language to use today? I think the only way to really judge how the changes will affect us is to take a closer look at the changes themselves and see both the good and the bad.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/04/an-objective-look-at-javascript-2-0-looking-back/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quicker DOM Traversing with CSS Selectors</title>
		<link>http://timkadlec.com/2008/03/quicker-dom-traversing-with-css-selectors/</link>
		<comments>http://timkadlec.com/2008/03/quicker-dom-traversing-with-css-selectors/#comments</comments>
		<pubDate>Thu, 06 Mar 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/quicker-dom-traversing-with-css-selectors/</guid>
		<description><![CDATA[After looking at XPath and how it can be used to quickly traverse the document tree, I also thought I'd take a look at the W3C Selectors API as it kind of falls in that same line.]]></description>
			<content:encoded><![CDATA[<p>After looking at XPath and how it can be used to quickly traverse the document tree, I also thought I&#8217;d take a look at the <a href="http://www.w3.org/TR/selectors-api/" target="_blank">W3C Selectors API</a> as it kind of falls in that same line. At this point, it none of the major browsers support it. However, any WebKit build (Safari&#8217;s engine) since February 7th supports it, and it looks like IE8 will be supporting it as well. I&#8217;d be eager to hear if anyone knows where Opera and Firefox stand on getting it going here in the future.</p>
<p>The Selectors API allows us to utilize CSS (1-3) selectors to collect nodes from the DOM. This is actually quite a common enhancement in a lot of Javascript libraries&#8230;.CSS selectors are a very efficient and powerful way to quickly look up nodes, and since most people are familiar with CSS syntax, it is very user friendly. The Selectors API offers native browser support for CSS selectors using the querySelector and querySelectorAll methods.</p>
<p>The querySelector method as defined by the W3C returns the first element matching the selector, or if no matching element is found, it returns a null value.</p>
<p>The querySelectorAll method returns a StaticNodeList of all elements matching the selector, or if no matching elements were found, it returns a null value. For anyone familiar with DOM traversal, you are probably familiar with NodeLists. NodeLists are returned by methods like getElementsByTagName. The main difference between the StaticNodeList and a NodeList, is that if you remove an element from the document, a NodeList is also affected and therefore the indexes of the NodeList are altered. A StaticNodeList, however, is not affected&#8230;hence the Static part.</p>
<p>The querySelector and querySelector methods are very easily used:<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>//returns all elements with an error class</li>
<li>document.querySelectorAll(".error");</li>
<li>//returns the first paragraph with an error class</li>
<li>document.querySelector("p.error");</li>
<li>//returns every other row of a table with an id of data</li>
<li>document.querySelectorAll("#data:nth-child(even)";</li>
</ol>
<p></code><br />
In addition to calling the methods with a single selector, you can also pass groups of selectors seperated by commas, like so:<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>document.querySelectorAll(".error, .warning");</li>
<li>document.querySelector(".error, .warning");</li>
</ol>
<p></code><br />
The first line above would return all elements with a class or error or a class of warning. The second line would return the first element with a class of either error or warning.</p>
<p>You can see the advantage of having native support for the SelectorAPI by taking a look at <a href="http://webkit.org/perf/slickspeed" target="_blank">some test results</a>. SlickSpeed runs the test cases using the popular Javascript libraries Prototype, JQuery and ext as well as by using the Selectors API and the results are substantially quicker using the Selectors API. To run the native support test, you will need to go grab the WebKit nightly build. If you don&#8217;t want to do that, <a href="http://blogs.vertigo.com/personal/rbiggs/Blog/Lists/Posts/Post.aspx?ID=33" target="_blank">Robert Biggs</a> ran the test in various browsers and has the test results up.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/03/quicker-dom-traversing-with-css-selectors/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>XPath in Javascript: Predicates and Compounds</title>
		<link>http://timkadlec.com/2008/02/xpath-in-javascript-predicates-and-compounds/</link>
		<comments>http://timkadlec.com/2008/02/xpath-in-javascript-predicates-and-compounds/#comments</comments>
		<pubDate>Tue, 19 Feb 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[xpath]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/xpath-in-javascript-predicates-and-compounds/</guid>
		<description><![CDATA[In this, the second part of my look at XPath and how it can be used in Javascript, we'll take a look at how we can use compounds and predicates to build more robust expressions.]]></description>
			<content:encoded><![CDATA[<p>Welcome to the second part of my look at XPath and how it can be used in Javascript. <a href="http://www.timkadlec.com/post.asp?q=47">Part one</a> served as a real basic introduction to what XPath is, how it can traverse the document tree, and an introduction to using XPath expressions in Javascript using the evaluate method. So far what we have seen is really basic. There is some value in it, but we can build much more robust expressions with a bit more knowledge.</p>
<h2>Getting More Detailed with Compounds</h2>
<p>So far, we haven&#8217;t dealt with any compound location paths&#8230;each of our expressions has just gotten nodes that are direct children of the context node. However, we can continue to move up and down the document tree by combining single location paths. One of the ways we can do this (and this should look quite familiar to anyone who has moved through directories elsewhere) is by using the forward slash &#8216;/&#8217;. The forward slash continues to move us one step down in the tree, relative to the preceding step.</p>
<p>For example, consider the following:<br />
<code></p>
<ol class="code">
<li>myXPath = "//div/h3/span"</li>
<li>var results = document.evaluate(myXPath, document, null, XPathResult.ANY_TYPE, null);</li>
</ol>
<p></code><br />
The expression above will first go to the root node thanks to our &#8216;//&#8217;. It will then get any div elements that are descendants of the root node. Then, we use the forward slash to move down one more level. Now we are saying to get all h3 elements that are direct descendants of one of the div elements that was returned. Finally, we once again use our forward slash to move down one more level, and tell the expression to return any span elements that are direct descendants of the h3 elements we already found.</p>
<p>In addition, we can use the double period &#8216;..&#8217; to select an elements parent nodes. For example, if we use an expression like &#8216;//@title&#8217;, we will get all title attributes in the document. Let&#8217;s say that what we actually wanted, is all elements in the document that have title attributes. Using the parent selector (..), we can do just that. The expression &#8216;//@title/..&#8217; first grabs all title attributes. Then the double period tells the expression to step back up and grab the parent node for each of those title attributes.</p>
<p>This is a pretty handy little feature. We can use the double period to select sibling elements by doing something like &#8216;//child/../sibling&#8217; where child is the child element, and sibling is the sibling element we are looking for. For example, &#8216;//h3/../p&#8217; would get all p elements that are siblings of h3 elements.</p>
<p>Finally, we can use a single period &#8216;.&#8217; to select the current node. You will see this become useful when we introduce the use of predicates.</p>
<h2>Speak Of the Devil</h2>
<p>Each expression we&#8217;ve seen returns a bunch of nodes matching criteria. Occasionally, we will want to refine this even further. We can do that using predicates, which are simply Boolean expressions that get tested for each node in our list. If the expression is false, the node is not returned in our results; if the expression is true, the node is returned.</p>
<p>Predicates use the typical Boolean operators, &#8216;+&#8217;, &#8216;&lt;&#8217;, &#8216;&gt;&#8217;, &#8216;&lt;=&#8217;, &#8216;&gt;=&#8217;, &#8216;!=&#8217;, &#8216;and&#8217; and &#8216;or&#8217;. As promised, the single period becomes much more useful when combined with predicates. For example, we can grab all h3 elements that have a value of &#8220;Yaddle&#8221; by using the following expression:</p>
<p><code></p>
<ul class="code">
<li>//h3[.="Yaddle"]</li>
</ul>
<p></code><br />
The dot tells the expression to check for the value of that current node. If the value equals &#8220;Yaddle&#8221;, the h3 will be returned to us. Let&#8217;s take a look at another example, one maybe a bit more practical. Let&#8217;s say you have a calendar of events, and all you want to retrieve all the events that occurred between 2005 and 2007. Being the smart developers we are, we wrapped all the event years in a span with a class of year, like so:<br />
<code></p>
<ul class="code">
<li>&lt;span class="year"&gt;2007&lt;/span&gt;</li>
</ul>
<p></code><br />
Getting all the year spans where the value is between 2005 and 2007 is easy. We can simply do this:<br />
<code></p>
<ul class="code">
<li>//span[@class="year"][.&lt;= 2007 and .&gt;=2005]</li>
</ul>
<p></code><br />
Ok&#8230;granted, at first glance that is pretty ugly, so let&#8217;s break it down.</p>
<ol class="reg">
<li><code>//span</code> &#8211; Get all span elements</li>
<li><code>[@class="year"]</code> &#8211; Make sure the only span elements we grab have a class of &#8216;year&#8217;</li>
<li><code>[.&gt;=2005 and .&lt;=2007]</code> &#8211; Make sure the value of span is between 2005 and 2007. We use the &#8216;&lt;=&#8217; and &#8216;&gt;=&#8217; operators versus the &#8216;&lt;&#8217; and &#8216;&gt;&#8217; operators because we want to also return values in the years 2005 and 2007.</li>
</ol>
<p>Making sense out of all the slashes and brackets can take some getting used to, so don&#8217;t be discouraged if it takes you awhile before you can make sense out of what is happening there. Once you get more familiar with the syntax used, you will find you can create some really robust checks in one line of code that would have taken numerous iterations using DOM methods.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/02/xpath-in-javascript-predicates-and-compounds/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>XPath in Javascript: Introduction</title>
		<link>http://timkadlec.com/2008/02/xpath-in-javascript-introduction/</link>
		<comments>http://timkadlec.com/2008/02/xpath-in-javascript-introduction/#comments</comments>
		<pubDate>Wed, 13 Feb 2008 03:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[xpath]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/xpath-in-javascript-introduction/</guid>
		<description><![CDATA[As reported by John Resig, Prototype, Dojo, and Mootools have all switched their CSS Selector engines to be using XPath expressions, which means now is a good time to get familiarized with them and what they can accomplish.]]></description>
			<content:encoded><![CDATA[<p>As reported by <a href="http://ejohn.org/blog/xpath-overnight/" target="_blank">John Resig</a>, Prototype, Dojo, and Mootools have all switched their CSS Selector engines to be using XPath expressions instead of traditional DOM methods. With the attention being placed on XPath expressions, now is a good time to get familiarized with them and what they can accomplish.</p>
<p>This is going to be a multi-post series, as there is just so much you can accomplish by using XPath expressions that if I tried putting it into one post, no one would have the time to sit and read the whole thing.</p>
<h2>What is XPath?</h2>
<p>Any of you out there who are familiar with XSLT will no doubt be familiar with the XPath language. For the rest of you, XPATH is used to identify different parts of XML documents by indicating nodes by position, relative position, type, content, etc.</p>
<p>Similar to the DOM, XPath allows us to pick nodes and sets of nodes out of our XML tree. As far as the language is concerned, there are seven different node types XPath has access to (for most Javascript purposes the first four node types will most likely be sufficient):</p>
<ol class="reg">
<li>Root Node</li>
<li>Element Nodes</li>
<li>Text Nodes</li>
<li>Attribute Nodes</li>
<li>Comment Nodes</li>
<li>Processing Instruction Nodes</li>
<li>Namespace Nodes</li>
</ol>
<h2>How Does XPath Traverse the Tree?</h2>
<p>XPath can use location paths, attribute location steps, and compound location paths to very quickly and efficiently retrieve nodes from our document. You can use simple location paths to quickly retrieve nodes you want to work with. There are two basic simple location paths &#8211; the root location path (/) and child element location paths.</p>
<p>The forward slash (/) servers as the root location path&#8230;it selects the root node of the document. It is important to realize this is not going to retrieve the root element, but the entire document itself. The root location path is an absolute location path&#8230;no matter what the context node is, the root location path will always refer to the root node.</p>
<p>Child element location steps are simply using a single element name. For example, the XPath <code>p</code> refers to all <code>p</code> children of our context node.</p>
<p>One of the really handy things with XPath is we have quick access to all attributes as well by using the at sign &#8216;@&#8217; followed by the attribute name we want to retrieve. So we can quickly retrieve all title attributes by using <code>@title</code>.</p>
<h2>Using XPath in Javascript</h2>
<p>That&#8217;s all well and fine, but how do we use this in Javascript? Right now, Opera, Firefox and Safari 3 all support the XPath specification (at least to some extent) and allow us to use the document.evaluate() method. Unfortunately at this time, IE offers no support for XPath expressions. (Let&#8217;s hope that changes in IE8)</p>
<p>The document.evaluate method looks like this:<br />
<code><br />
</code></p>
<p><code></p>
<ul class="code">
<li>var theResult = document.evaluate(expression, contextNode, namespaceResolver, resultType, result);</li>
</ul>
<p></code><br />
The <code>expression</code> argument is simply a string containing the XPath expression we want evaluated. The <code>contextNode</code> is the node we want the expression evaluated against. The <code>namespaceResolver</code> can safely be set to null in most HTML applications. The <code>resultType</code> is a constant telling what type of result to return. Again, for most purposes, we can just use the <code>XPathResult.ANY_TYPE</code> constant which will return whatever the most natural result would be. Finally, the <code>result</code> argument is where we could pass in an existing XPathResult to use to store the results in. If we don&#8217;t have an XPathResult to pass in, we just set this value to <code>null</code> and a new XPathResult will be created.</p>
<p>Ok&#8230;all that talk and still no code. Let&#8217;s remedy that shall we. Here&#8217;s a very simple XPath expression that will return all elements in our document with a title attribute.<br />
<code><br />
</code></p>
<p><code></p>
<ul class="code">
<li>var titles = document.evaluate("//*[@title]", document, null, XPathResult.ANY_TYPE, null);</li>
</ul>
<p></code><br />
If you take a look at the XPath expression we passed in &#8220;//*[@title]&#8220;, you will notice that we used the attribute location step followed by the attribute we want to find, &#8216;title&#8217;. The two forward slashes preceding the at sign is how we tell the browser to select from all descendants of the root node (the document). The asterisk sign says to grab any nodes regardless of the type. Then we use the square brackets in combination with our attribute selector to limit our results only to nodes with a title attribute.</p>
<p>The evaluate method in this case returns an <code>UNORDERED_NODE_ITERATOR_TYPE</code>, which we can now move through by using the <code>iterateNext()</code> method like so:<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>var theTitle = titles.iterateNext();</li>
<li>while (theTitle){</li>
<li class="tab1">alert(theTitle.textContent);</li>
<li class="tab1">theTitle = titles.iterateNext();</li>
<li>}</li>
</ol>
<p></code><br />
Since each item in the results is a node, we need to reference the text inside of it by using the <code>textContent</code> property (line 3). You can only iterate to a node once, so if you want to use your results later, you could save each node off into an array with something like below:<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>var arrTitles = [];</li>
<li>var theTitle = titles.iterateNext();</li>
<li>while (theTitle){</li>
<li class="tab1">arrTitles.push(theTitle.textContent);</li>
<li class="tab1">theTitle = titles.iterateNext();</li>
<li>}</li>
</ol>
<p></code><br />
Now <code>arrTitles</code> is filled with your results and you can use them however often you wish.</p>
<p>This is just the beginning&#8230;as we continue to look at XPath expressions and introduce predicates and XPath functions, you will start to see just how truly robust XPath expressions are. At this point, IE doesn&#8217;t support using XPath expressions in Javascript, but with each of the other major browsers having some support, and major Javascript Libraries placing an emphasis on using them, it&#8217;s only a matter of time before we can begin using these expressions to create more efficient code.</p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/02/xpath-in-javascript-introduction/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Display a Link&#039;s Href When Printing</title>
		<link>http://timkadlec.com/2008/01/display-a-links-href-when-printing/</link>
		<comments>http://timkadlec.com/2008/01/display-a-links-href-when-printing/#comments</comments>
		<pubDate>Tue, 22 Jan 2008 00:00:00 +0000</pubDate>
		<dc:creator>tkadlec</dc:creator>
				<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://localhost/1969/12/display-a-links-href-when-printing/</guid>
		<description><![CDATA[Using print stylesheets are a nice way to enhance a user's experience of a site. Our screen stylesheets don't necessarily turn out that nicely when printed out, so using a few different CSS rules on our print stylesheet we can increase readability and usability.]]></description>
			<content:encoded><![CDATA[<p>Using print stylesheets are a nice way to enhance a user&#8217;s experience of a site. Our screen stylesheets don&#8217;t necessarily turn out that nicely when printed out, so using a few different CSS rules on our print stylesheet we can increase readability and usability.</p>
<p>One of those nice features we can add is to display a link&#8217;s href directly after the link on our print-outs. This will allow someone who has printed out the page to still be able to know where the links on the page are pointing to. We can do this with CSS by using the :after psuedo-class and some generated content.<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>a[href]:after{</li>
<li class="tab1">content: " [" attr(href) "] ";</li>
<li>}</li>
</ol>
<p></code><br />
There are really four important parts of the statement above:</p>
<ol class="reg">
<li><code>a[href]</code>: Here, we use an attribute selector to select all links in our page with an href attribute.</li>
<li><code>:after</code>: The :after pseudo-class allows us to insert some content after the links and style it if necessary.</li>
<li><code>content</code>: This is what actually generates the content. We could just insert, for example, the letter &#8220;a&#8221; with a style call like content: &#8220;a&#8221;.</li>
<li><code>attr(href)</code>: This gets the href attribute of the link currently being styled. This way, each link will display it&#8217;s own href.</li>
</ol>
<p>If we put this style in our print stylesheet, all of our links that actually have an href will print out like this: TimKadlec.com [http://www.timkadlec.com]</p>
<p>Obviously, this is a pretty handy enhancement to our print stylesheets. Now, the links printed out actually have some meaning to them. The problem is, Internet Explorer doesn&#8217;t support the :after pseudo class, nor does it support the content style. So if a user is using Internet Explorer and tries to print our page out, they still won&#8217;t see any href&#8217;s displayed.</p>
<h2>Javascript to the Rescue</h2>
<p>We can use a little bit of browser specific Javascript to fix this problem. Internet Explorer (version 5.0 and up) has a little known proprietary event called onbeforeprint. Just like it sounds, this event fires right before printing a page or viewing a print preview of the page. Since IE is the only major browser that doesn&#8217;t create the effect using CSS, a proprietary event is the perfect fix. Now, we can draw up a simple function like so:<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>window.onbeforeprint = function(){</li>
<li class="tab1">var links = document.getElementsByTagName("a");</li>
<li class="tab1">for (var i=0; i&lt; links.length; i++){</li>
<li class="tab2">var theContent = links[i].getAttribute("href");</li>
<li class="tab2">if (!theContent == ""){</li>
<li class="tab3">links[i].newContent = " [" + theContent + "] ";</li>
<li class="tab3">links[i].innerHTML = links[i].innerHTML + links[i].newContent;</li>
<li class="tab2">}</li>
<li class="tab1">}</li>
<li>}</li>
</ol>
<p></code><br />
Our function simply gets all the links on a page, and appends their respective href&#8217;s immediately after them, creating the same effect that we were able to do using CSS in other browsers. You might be wondering why we set the new content we created to be a property of each link. That&#8217;s because right after printing or canceling out of the print preview screen, we are now seeing the href on our actual web site. We obviously don&#8217;t want this, and it&#8217;s simple enough to get rid of with another IE proprietary function, onafterprint.<br />
<code><br />
</code></p>
<p><code></p>
<ol class="code">
<li>window.onafterprint = function(){</li>
<li class="tab1">var links = document.getElementsByTagName("a");</li>
<li class="tab1">for (var i=0; i&lt; links.length; i++){</li>
<li class="tab2">var theContent = links[i].innerHTML;</li>
<li class="tab2">if (!theContent == ""){</li>
<li class="tab3">var theBracket = theContent.indexOf(links[i].newContent);</li>
<li class="tab3">var newContent = theContent.substring(0, theBracket);</li>
<li class="tab3">links[i].innerHTML = newContent;</li>
<li class="tab2">}</li>
<li class="tab1">}</li>
<li>}</li>
</ol>
<p></code><br />
Here we just again, loop through all the links, find the position of the new content we added, and remove it from the link. This returns the appearance of our site to the original view before trying to print.</p>
<p>Obviously, it would be ideal if we could simply use CSS to manage this. However, as we&#8217;ve seen, there is no need to wait for IE to support this feature before we implement it. Some proprietary Javascript events allow us to replicate the effect until it is supported later on.</p>
<p>The script/css effect has been tested in IE7, Opera, Firefox, and Safari. If you are interested, the complete Javascript to create the effect in IE is here: <a href="scripts/printlinks.js">printlinks.js</a></p>
]]></content:encoded>
			<wfw:commentRss>http://timkadlec.com/2008/01/display-a-links-href-when-printing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
