<?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>sociomantic labs &#124; Real-time bidding solutions for eCommerce &#187; Code Talk</title>
	<atom:link href="http://blog.sociomantic.com/category/code-talk/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.sociomantic.com</link>
	<description>Real-time bidding solutions for eCommerce</description>
	<lastBuildDate>Thu, 17 May 2012 08:27:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Native Javascript Ninjutsu: Navigator object browser detection</title>
		<link>http://blog.sociomantic.com/2010/11/native-javascript-ninjutsu-navigator-object-browser-detection/</link>
		<comments>http://blog.sociomantic.com/2010/11/native-javascript-ninjutsu-navigator-object-browser-detection/#comments</comments>
		<pubDate>Mon, 08 Nov 2010 11:35:49 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[browser detection]]></category>
		<category><![CDATA[cross-browser]]></category>
		<category><![CDATA[cross-browser compatibility]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[navigator object]]></category>
		<category><![CDATA[navigator.userAgent]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2778</guid>
		<description><![CDATA[The training continues. How many programmers can write pure native JS without the aid of a framework? Discipline 9 of the series is a lesson about cross-browser compatibility. "Even in the worst case scenario I try extremely hard to find clever solutions that allow me to avoid relying on browser detection. Despite this practice and frame of mind I still believe it’s useful for native JS ninjas to understand how to use browser detection techniques.]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <acronym title="Asynchronous JavaScript and XML">AJAX</acronym> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 8: Tenmon (meteorology)</strong></p>
<p>In my daily <abbr title="Javascript">JS</abbr> missions I do my very best to make sure my code is fully cross-browser compatible. Even in the worst case scenario I try extremely hard to find clever solutions that allow me to avoid relying on browser detection. Despite this practice and frame of mind I still believe it&#8217;s useful for native <abbr title="Javascript">JS</abbr> ninjas to understand how to use browser detection techniques.</p>
<p>Let&#8217;s first take a look at the <code>navigator</code> object. While it has some useful properties and methods, it&#8217;s very important to remember that they can &#8211; and often will &#8211; return inaccurate and misleading information. This is not only because there is no public standard for this object (and its methods and properties), but also because some of its properties (such as the <code>navigator.userAgent</code>) are extremely easy to spoof. You&#8217;ll want to note that I&#8217;ll be using Firefox version 3.6.12 (with cookies and Java enabled) on Windows 7 (in English) for the following examples, and thus if you test my code snippets within your work environment you may not (and most likely won&#8217;t) see the same results returned.</p>
<p><strong>navigator.appCodeName</strong></p>
<p>The <code>navigator.appCodeName</code> property will return the code name of the browser:</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_code_name = navigator.appCodeName;
</pre>
<p>The above code will return &#8220;Mozilla&#8221; for my browser settings and environment.</p>
<p><strong>navigator.appName</strong></p>
<p>The <code>navigator.appName</code> property will return the name of browser.</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_name = navigator.appName;
</pre>
<p>The above code will return &#8220;Netscape&#8221; for my browser settings and environment.</p>
<p><strong>navigator.appVersion</strong></p>
<p>The <code>navigator.appVersion</code> property will return the version information of the browser.</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_version = navigator.appVersion;
</pre>
<p>The above code will return &#8220;5.0 (Windows; en-GB)&#8221; for my browser settings and environment.</p>
<p><strong>navigator.cookieEnabled</strong></p>
<p>The <code>navigator.cookieEnabled</code> property will return whether or not cookies are enabled in the browser.</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_cookie_enabled = navigator.cookieEnabled;
</pre>
<p>The above code will return &#8220;true&#8221; for my browser settings and environment.</p>
<p><strong>navigator.platform</strong></p>
<p>The <code>navigator.platform</code> property will return which platform the browser was built to run on.</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_platform = navigator.platform;
</pre>
<p>The above code will return &#8220;Win32&#8243; for my browser settings and environment.</p>
<p><strong>navigator.userAgent</strong></p>
<p>The <code>navigator.userAgent</code> property will return the user-agent header that the browser sends to the server.</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_user_agent = navigator.userAgent;
</pre>
<p>The above code will return &#8220;Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12&#8243; for my browser settings and environment.</p>
<p><strong>navigator.javaEnabled()</strong></p>
<p>The <code>navigator.javaEnabled()</code> method will determine whether or not Java is enabled.</p>
<pre class="brush: jscript; title: ; notranslate">
var browser_java_enabled = navigator.javaEnabled();
</pre>
<p>The above code will return &#8220;true&#8221; for my browser settings and environment.</p>
<p><strong>20 Browsers Worth Testing</strong></p>
<p>Now that we&#8217;ve become a bit more familiar with the <code>navigator</code> object let&#8217;s take a look at the various browsers available to our users. It&#8217;s important to understand that while a majority of users may have upgraded to one of the more modern web browsers (and their most recent release versions), there may still be a significant number of visitors using out-of-date browsers and older versions. Because of this I do my very best to support a wide range of browsers in my <abbr title="Cascading Style Sheets">CSS</abbr>, <abbr title="HyperText Markup Language">HTML</abbr>, and <abbr title="Javascript">JS</abbr> production. I currently test 20 different browsers for each mission I embark on:</p>
<ul>
<li><abbr title="Microsoft Internet Explorer version 9">IE9</abbr></li>
<li><abbr title="Microsoft Internet Explorer version 8">IE8</abbr></li>
<li><abbr title="Microsoft Internet Explorer version 7">IE7</abbr></li>
<li><abbr title="Microsoft Internet Explorer version 6">IE6</abbr></li>
<li><abbr title="Mozilla Firefox version 4">FF4</abbr></li>
<li><abbr title="Mozilla Firefox version 3.6">FF3.6</abbr></li>
<li><abbr title="Mozilla Firefox version 3.5">FF3.5</abbr></li>
<li><abbr title="Mozilla Firefox version 3">FF3</abbr></li>
<li><abbr title="Mozilla Firefox version 2">FF2</abbr></li>
<li><abbr title="Google Chrome 9">Chrome 9</abbr></li>
<li><abbr title="Google Chrome 8">Chrome 8</abbr></li>
<li><abbr title="Google Chrome 7">Chrome 7</abbr></li>
<li><abbr title="Google Chrome 6">Chrome 6</abbr></li>
<li><abbr title="Google Chrome 5">Chrome 5</abbr></li>
<li><abbr title="Google Chrome 4">Chrome 4</abbr></li>
<li><abbr title="Apple Safari 5">Safari 5</abbr></li>
<li><abbr title="Apple Safari 4">Safari 4</abbr></li>
<li><abbr title="Apple Safari 3">Safari 3</abbr></li>
<li>Opera 10</li>
<li>Opera 9</li>
</ul>
<p>I only consider a web project fully cross-browser compatible if it works in all of the above browsers and versions.</p>
<p><strong>Browser Detection</strong></p>
<p>Detecting the above 20 browsers using the <code>navigator</code> object can seem daunting at first as many of the <code>navigator</code> properties do not return what one might expect. I did a series of tests in Windows 7 using all the above browsers and determined that the most accurate and simplest way for me to detect the browser was to read the returned value of the <code>navigator.userAgent</code>. Now this may seem obvious to experienced users, but I hope that this will tip will help beginners avoid the mistake of attempting to rely on the likes of <code>navigator.appCodeName</code>, <code>navigator.appName</code>, and <code>navigator.appVersion</code>.</p>
<p>After that I went through each browser and looked for a unique part of the user-agent header that I could use to properly identify each browser and version. Fortunately these unique strings are pretty straight forward and quite human-readable. Below you can see some example <abbr title="Javascript">JS</abbr> that will attempt to detect the browser name and version number based on the existence of various strings in the <code>navigator.userAgent</code> property:</p>
<pre class="brush: jscript; title: ; notranslate">
var browser = navigator.userAgent;
var browser_name = 'Unknown';
var browser_version = 'Unknown';

if ( browser.indexOf( 'MSIE' ) !== -1 )
{
    browser_name = 'Microsoft Internet Explorer';

    if ( browser.indexOf( 'MSIE 6' ) !== -1 )
    {
        browser_version = '6';
    }
    else if ( browser.indexOf( 'MSIE 7' ) !== -1 )
    {
        browser_version = '7';
    }
    else if ( browser.indexOf( 'MSIE 8' ) !== -1 )
    {
        browser_version = '8';
    }
    else if ( browser.indexOf( 'MSIE 9' ) !== -1 )
    {
        browser_version = '9';
    }
}
else if ( browser.indexOf( 'Firefox' ) !== -1 )
{
    browser_name = 'Mozilla Firefox';

    if ( browser.indexOf( 'Firefox/4' ) !== -1 )
    {
        browser_version = '4';
    }
    else if ( browser.indexOf( 'Firefox/3.6' ) !== -1 )
    {
        browser_version = '3.6';
    }
    else if ( browser.indexOf( 'Firefox/3.5' ) !== -1 )
    {
        browser_version = '3.5';
    }
    else if ( browser.indexOf( 'Firefox/3' ) !== -1 )
    {
        browser_version = '3';
    }
    else if ( browser.indexOf( 'Firefox/2' ) !== -1 )
    {
        browser_version = '2';
    }
}
else if ( browser.indexOf( 'Chrome' ) !== -1 )
{
    browser_name = 'Google Chrome';

    if ( browser.indexOf( 'Chrome/4' ) !== -1 )
    {
        browser_version = '4';
    }
    else if ( browser.indexOf( 'Chrome/5' ) !== -1 )
    {
        browser_version = '5';
    }
    else if ( browser.indexOf( 'Chrome/6' ) !== -1 )
    {
        browser_version = '6';
    }
    else if ( browser.indexOf( 'Chrome/7' ) !== -1 )
    {
        browser_version = '7';
    }
    else if ( browser.indexOf( 'Chrome/8' ) !== -1 )
    {
        browser_version = '8';
    }
    else if ( browser.indexOf( 'Chrome/9' ) !== -1 )
    {
        browser_version = '9';
    }
}
else if ( browser.indexOf( 'Safari' ) !== -1 )
{
    browser_name = 'Apple Safari';

    if ( browser.indexOf( 'Version/3' ) !== -1 )
    {
        browser_version = '3';
    }
    else if ( browser.indexOf( 'Version/4' ) !== -1 )
    {
        browser_version = '4';
    }
    else if ( browser.indexOf( 'Version/5' ) !== -1 )
    {
        browser_version = '5';
    }
}
else if ( browser.indexOf( 'Opera/9' ) !== -1 )
{
    browser_name = 'Opera';
    browser_version = '9';

    if ( browser.indexOf( 'Version/10' ) !== -1 )
    {
        browser_version = '10';
    }
}
</pre>
<p>Although the above code works like a charm in my test environment, it&#8217;s extremely important to remember that the user-agent header is very easy to spoof. Again &#8211; in order to not alarm and enrage the experienced coders out there and also to properly guide and inform the beginners &#8211; I want to explicitly state that the above method of browser detection is not at all a replacement for building cross-browser compatible code to begin with. I highly suggest you design your <abbr title="Cascading Style Sheets">CSS</abbr>, <abbr title="HyperText Markup Language">HTML</abbr>, and <abbr title="Javascript">JS</abbr> to work in all browsers without the need to rely on browser detection techniques.</p>
<p>I personally only use <abbr title="Javascript">JS</abbr> browser detection in my own &#8216;sandbox&#8217; (a local test environment for front-end web development) and I do so there because it&#8217;s easy to forget which browser (and version number) I&#8217;m currently viewing when I need to test each file in all 20 of the above listed browsers. Human error is natural and in such an environment I&#8217;m simply using the browser detection to provide me with an easy way to display the current test browser and version number. Remember: I&#8217;m acting as the user and thus I know that the user-agent header is accurate and not being spoofed.</p>
<p><strong>Cross-Browser Compatibility Test Environment</strong></p>
<p>I&#8217;ll admit that I&#8217;m no expert on the many web applications and desktop software solutions that exist out there for doing cross-browser compatibility testing. I actually prefer to do as much of my testing by hand whenever possible. I currently have a test environment that I particularly like and find to be useful, fast, and quite reliable. It consists of a local &#8216;sandbox&#8217; I&#8217;ve developed, which is, in essence, simply an archive of test files. I have setup a local host so that the &#8216;sandbox&#8217; can be quickly reached with the short URL: &#8216;http://sandbox&#8217;.</p>
<p>In addition to my locally installed web browsers I also run the <a title="Spoon Browser Sandbox" href="http://spoon.net/browsers/" target="_blank">Spoon Browser Sandbox</a> and make sure that all of the browsers&#8217; homepages are set to my &#8216;sandbox&#8217; host (with the exception of <abbr title="Microsoft Internet Explorer version 9">IE9</abbr> Preview which currently does not allow a homepage to be set). This means I can quickly and efficiently check a single test in numerous browsers, one after the other, with only a few clicks and without needing to have said browsers actually installed on my machine. I open a test browser and it immediately jumps to my list of test files, I select one, see the results (success or failure), make note of the browser and version number that my <abbr title="Javascript">JS</abbr> detection displays in the top corner, close the browser, and repeat the process.</p>
<p>This is only one solution to building a cross-browser compatibility test environment and I&#8217;m very open to hearing the other options people use. Please leave a comment if you have found (or made) a test environment that you think is particularly clever, useful, or otherwise worth mentioning. For those beginners out there I hope this article has helped to steer you in the right direction, informing you of the importance of not relying on <abbr title="Javascript">JS</abbr> browser detection, but also providing you the necessary means to attempt browser detection whenever it may be useful or interesting.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a><br />
Discipline 3: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Include External JS</a><br />
Discipline 4: <a title="Native Javascript Ninjutsu: Cookie and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">Cookies and Variables</a><br />
Discipline 5: <a title="Native Javascript Ninjutsu: removeNode vs. removeChild" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/">removeNode vs. removeChild</a><br />
Discipline 6: <a title="Native Javascript Ninjutsu: DOMinating iframes" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/">DOMinating iframes</a><br />
Discipline 7: <a title="Native Javascript Ninjutsu: Document object methods &amp; properties" href="http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/">Document object methods &amp; properties</a><br />
Discipline 8: <a title="Native Javascript Ninjutsu: Window object methods &amp; properties" href="http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-window-object-methods-properties/">Window object methods &amp; properties</a></p>
<p><strong>Resources</strong><br />
<a title="W3Schools' Navigator Object Reference" href="http://www.w3schools.com/jsref/obj_navigator.asp">W3Schools&#8217; Navigator Object Reference</a><br />
<a title="Spoon Browser Sandbox" href="http://spoon.net/browsers/" target="_blank">Spoon Browser Sandbox</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/11/native-javascript-ninjutsu-navigator-object-browser-detection/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>D-tails 1: local this</title>
		<link>http://blog.sociomantic.com/2010/11/d-tails-1-local-this/</link>
		<comments>http://blog.sociomantic.com/2010/11/d-tails-1-local-this/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 13:20:39 +0000</pubDate>
		<dc:creator>Gavin</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[back-end development]]></category>
		<category><![CDATA[D language]]></category>
		<category><![CDATA[D programming language]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2796</guid>
		<description><![CDATA[This is the first in an on-going series of posts relating nuggets of D wisdom gained through daily praxis. 

I recently came across the situation where I needed to pass a pointer to an object to a callback function in a C library. The function was designed so that you can pass 'additional data' by means of a void*, which could be used to point to any kind of data in memory which would contain the context for the callback. This is a fairly common pattern in C libraries, designed to make the callbacks flexible and extensible to any use case.]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.sociomantic.com/wp-content/uploads/Sign_language_D.png"><img class="alignright  wp-image-2804" title="Sign_language_D" src="http://blog.sociomantic.com/wp-content/uploads/Sign_language_D-190x300.png" alt="" /></a>This is the first in an on-going series of posts relating nuggets of D wisdom gained through daily praxis.</p>
<p><strong>&#8220;<code>this</code> is a local variable&#8221;</strong></p>
<p>I recently came across the situation where I needed to pass a pointer to an object to a callback function in a C library. The function was designed so that you can pass &#8216;additional data&#8217; by means of a <code>void*</code>, which could be used to point to any kind of data in memory which would contain the context for the callback. This is a fairly common pattern in C libraries, designed to make the callbacks flexible and extensible to any use case.</p>
<p>Here&#8217;s a simplified example of the situation:</p>
<pre class="brush: d; title: ; notranslate">
class MyClass
{
	// Method to register a request with the C library, passing a reference
	// to this object as the 'context', which will be passed to the C callback
	// function below when the request is processed.
	void register ( )
	{
		void* pointer_to_this /* = ? */;
		CLibraryFunction(pointer_to_this);
	}

	// Callback
	extern ( C ) static private void callback ( void* context )
	{
		// somehow cast the 'context' argument to an object reference
		// and do something with it
	}
}
</pre>
<p>So the question is, how to get the address of an object, from inside it, to pass to the C library function? And how to convert it back to a usable object reference inside the callback function?</p>
<p>My initial instinct was:</p>
<pre class="brush: d; title: ; notranslate">
	void* pointer_to_this = &amp;this;
</pre>
<p>Sounds fair enough, right? But unfortunately it&#8217;s not that simple. After some research I turned up the fairly obscure fact that <code>this</code> is actually a local variable which is implicitly added to the every method&#8217;s parameter list. This means that by taking the address of <code>this</code>, all we get is a pointer to somewhere in the stack, which is not at all what was intended!</p>
<p>The solution is to think about what <code>this</code> actually is: a reference to an object. So we can cast the reference directly to a <code>void*</code>, and then cast it directly back &#8211; there&#8217;s no need to take the address of it or to dereference it at the other end using the <code>*</code> operator.</p>
<pre class="brush: d; title: ; notranslate">
class MyClass
{
	// Method to register a request with the C library, passing a reference
	// to this object as the 'context', which will be passed to the C callback
	// function below when the request is processed.
	void register ( )
	{
		void* pointer_to_this = cast(void*)this;
		CLibraryFunction(pointer_to_this);
	}

	// Callback
	extern ( C ) static private void callback ( void* context )
	{
		MyClass object = cast(MyClass)context;
		// do something with object
	}
}
</pre>
<p>More D language &#8220;D-tails&#8221; to come.</p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/11/d-tails-1-local-this/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: Window object methods &amp; properties</title>
		<link>http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-window-object-methods-properties/</link>
		<comments>http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-window-object-methods-properties/#comments</comments>
		<pubDate>Thu, 21 Oct 2010 10:39:42 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[webdev]]></category>
		<category><![CDATA[window methods]]></category>
		<category><![CDATA[window object]]></category>
		<category><![CDATA[window properties]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2605</guid>
		<description><![CDATA[The training continues. How many programmers can write pure native JS without the aid of a framework? Discipline 8 of the series is another lesson for beginners. Last week's article covered the most useful properties and methods of the document object, so this week I'd like to zoom out a bit and explore the window object. Just like the document object, the window object has a variety of its own properties, objects, and methods, though we'll only go over the most useful and interesting ones.]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 8: Sui-ren (water training)</strong></p>
<p class="note">NOTE: This article was written with the <abbr title="Javascript">JS</abbr> beginner in mind, so it will likely bore the rest of you!</p>
<p><a title="Native Javascript Ninjutsu: Document object methods &amp; properties" href="http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/">Last week&#8217;s article</a> covered the most useful properties and methods of the <code>document</code> object, so this week I&#8217;d like to zoom out a bit and explore the <code>window</code> object. Just like the <code>document</code> object, the <code>window</code> object has a variety of its own properties, objects, and methods, though we&#8217;ll only go over the most useful and interesting ones. Here&#8217;s a quick list of what we&#8217;ll discuss:</p>
<p>Properties/Objects:</p>
<ul>
<li><a href="#window.document"><code>window.document</code></a></li>
<li><a href="#window.frames"><code>window.frames</code></a></li>
<li><a href="#window.length"><code>window.length</code></a></li>
<li><a href="#window.location"><code>window.location</code></a></li>
<li><a href="#window.name"><code>window.name</code></a></li>
<li><a href="#window.navigator"><code>window.navigator</code></a></li>
<li><a href="#window.parent"><code>window.parent</code></a></li>
<li><a href="#window.self"><code>window.self</code></a></li>
<li><a href="#window.top"><code>window.top</code></a></li>
</ul>
<p>Methods:</p>
<ul>
<li><a href="#alert"><code>alert</code></a></li>
<li><a href="#confirm"><code>confirm</code></a></li>
<li><a href="#prompt"><code>prompt</code></a></li>
<li><a href="#setInterval"><code>setInterval</code></a></li>
<li><a href="#clearInterval"><code>clearInterval</code></a></li>
<li><a href="#setTimeout"><code>setTimeout</code></a></li>
<li><a href="#clearTimeout"><code>clearTimeout</code></a></li>
<li><a href="#window.open"><code>window.open</code></a></li>
<li><a href="#window.close"><code>window.close</code></a></li>
<li><a href="#window.focus"><code>window.focus</code></a></li>
<li><a href="#window.blur"><code>window.blur</code></a></li>
</ul>
<p>Let&#8217;s take a look at some of the most useful (and cross-browser compatible) properties first:</p>
<p><strong id="window.document">window.document</strong></p>
<p>We&#8217;ve already discussed the <code>document</code> object in the <a title="Native Javascript Ninjutsu: Document object methods &amp; properties" href="http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/">previous article</a> so I won&#8217;t go into detail, though it&#8217;s important to note that this object is a property of the <code>window</code> object.</p>
<p><strong id="window.frames">window.frames</strong></p>
<p>The <code>window.frames</code> property stores an array of all the frames in the given window. You can access a particular frame by providing it&#8217;s index number (remember that the index count of an array begins with 0, not 1):</p>
<pre class="brush: jscript; title: ; notranslate">
var first_frame = window.frames[0];
var second_frame = window.frames[1];
</pre>
<p>Once you&#8217;ve referenced a particular frame using the <code>frames</code> property you can access its properties:</p>
<pre class="brush: jscript; title: ; notranslate">
var first_frame = window.frames[0];
var second_frame = window.frames[1];
var first_frame_source = first_frame.location;
var second_frame_source = second_frame.location;
</pre>
<p>You can read more about the <code>frames</code> property in my previous post, <a title="Native Javascript Ninjutsu: DOMinating iframes" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/">DOMinating iframes</a>.</p>
<p><strong id="window.length">window.length</strong></p>
<p>The <code>window.length</code> property stores the number of frames in the given window. This should return the same result as <code>window.frames.length</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
var number_of_frames = window.length;
</pre>
<p><strong id="window.location">window.location</strong></p>
<p>The <code>window.location</code> property is actually an object which stores all the data about the given window&#8217;s current <abbr title="Uniform Resource Locator">URL</abbr>:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url = window.location;
</pre>
<p>The <code>location</code> object also has its own properties for returning various parts of the <abbr title="Uniform Resource Locator">URL</abbr>. The <code>location.href</code> property will also return the entire <abbr title="Uniform Resource Locator">URL</abbr>:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url = window.location.href;
</pre>
<p>The <code>protocol</code> property will return the protocol being used (such as HTTP, HTTPS, FTP, FTPS, etc):</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url_protocol = window.location.protocol;
</pre>
<p>The <code>port</code> property will return the port being used (if one was explicitly provided):</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url_port = window.location.port;
</pre>
<p>The <code>host</code> and <code>hostname</code> properties will return the host part of the <abbr title="Uniform Resource Locator">URL</abbr>:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url_host = window.location.host;
var the_current_url_host = window.location.hostname;
</pre>
<p>The <code>pathname</code> property will return the full path of the current <abbr title="Uniform Resource Locator">URL</abbr>:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url_path = window.location.pathname;
</pre>
<p>The <code>hash</code> property will return the anchor of the current <abbr title="Uniform Resource Locator">URL</abbr> (if one is provided):</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url_hash = window.location.hash;
</pre>
<p>The <code>search</code> property will return the query parameters of the current <abbr title="Uniform Resource Locator">URL</abbr> (if any ar provided):</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_url_query_parameters = window.location.search;
</pre>
<p>The <code>location</code> object also has some of its own methods, but I hardly ever use them in my native <abbr title="Javascript">JS</abbr> missions so I won&#8217;t explain them here.</p>
<p><strong id="window.name">window.name</strong></p>
<p>The <code>window.name</code> property stores the value of the window&#8217;s <code>name</code> attribute. You can retrieve and set this value:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_old_name = window.name;
window.name = 'the new window name';
</pre>
<p><strong id="window.navigator">window.navigator</strong></p>
<p>The <code>window.navigator</code> object can be quite an extensive subject and I find it deserves its own article, so I&#8217;ll be discussing the <code>navigator()</code> object in the next post in this series. Stay tuned for that if you&#8217;d like some more detailed info about this property.</p>
<p><strong id="window.parent">window.parent</strong></p>
<p>The <code>window.parent</code> property references the parent of the given window:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_parent = window.parent;
</pre>
<p>This can also be used recursively:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_parent = window.parent;
var the_grandparent = window.parent.parent;
</pre>
<p><strong id="window.self">window.self</strong></p>
<p>The <code>window.self</code> property allows you to reference the current window:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_current_window = window.self;
</pre>
<p><strong id="window.top">window.top</strong></p>
<p>The <code>window.top</code> property allows you to reference the topmost window:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_topmost_window = window.top;
</pre>
<p>There are many more properties that belong to the <code>window</code> object, though these are the ones that I find most useful in real-world applications. These are also the ones that I&#8217;ve found to be fully cross-browser compatible and <abbr title="Word Wide Web Consortium">W3C</abbr> compliant in my testing and research. Let&#8217;s continue our exploration of the <code>window</code> object by looking at a few of it&#8217;s most useful methods:</p>
<p><strong id="alert">alert()</strong></p>
<p>The <code>alert()</code> method is one of the most useful and commonly applied functions I can think of: it&#8217;s used constantly in early production, testing, and debugging stages of any native <abbr title="Javascript">JS</abbr> code. It&#8217;s fully cross-browser compatible and incredibly easy to use:</p>
<pre class="brush: jscript; title: ; notranslate">
alert( 'This is the alert message' );
</pre>
<p>The above code will open an alert box in the browser and display your message within it.</p>
<p><strong id="confirm">confirm()</strong></p>
<p>Very similar to <code>alert()</code>, the <code>confirm()</code> method will open a confirmation box in the browser that will include your message, an &#8216;OK&#8217; button and a &#8216;Cancel&#8217; button. It&#8217;s also cross-browser compatible and fairly easy to use:</p>
<pre class="brush: jscript; title: ; notranslate">
confirm( 'This is the confirmation message' );
</pre>
<p>The message is optional but it&#8217;s wise to include one, otherwise your users won&#8217;t know what they are confirming. Now if you want to check for which button the user has pushed you can do the following:</p>
<pre class="brush: jscript; title: ; notranslate">
var user_pushed_ok = confirm( 'This is the confirmation message' );
if ( user_pushed_ok == true )
{
    // User pushes 'OK'
}
else
{
    // User pushed 'Cancel'
}
</pre>
<p><strong id="prompt">prompt()</strong></p>
<p>The <code>prompt()</code> method is similar to both the <code>alert()</code> and the <code>confirm()</code> methods: it opens a browser alert message. The difference is that <code>prompt()</code> prompts the user to input some text. Again, it&#8217;s relatively simple to use:</p>
<pre class="brush: jscript; title: ; notranslate">
prompt( 'This is the prompt message' );
</pre>
<p>Just like <code>confirm()</code> the first parameter is optional. You can also provide a second parameter to specify if there should be default text filled in for the user:</p>
<pre class="brush: jscript; title: ; notranslate">
prompt( 'This is the prompt message', 'This is the default text' );
</pre>
<p>In order to use the text inputted by the user you&#8217;ll have to save the returned value of the method to a variable (as we do above with the <code>confirm()</code> method):</p>
<pre class="brush: jscript; title: ; notranslate">
var the_user_input = prompt( 'This is the prompt message', 'This is the default text' );
</pre>
<p><strong id="setInterval">setInterval()</strong></p>
<p>The <code>setInterval()</code> method is used to trigger a piece of code (typically a function call) over and over again until either the window is closed or the <code>clearInterval()</code> method has been called (see below for a description of this method). The method takes three parameters: the code to execute, the interval between executions (in milliseconds), and the script language (optional). For the sake of simplicity in this article we will just focus on the first two parameters:</p>
<pre class="brush: jscript; title: ; notranslate">
function theMethodToRepeat()
{
    // Do something
}

setInterval( 'theMethodToRepeat()', 5000 );
</pre>
<p>The above code will call <code>theMethodToRepeat()</code> function every five seconds. This will happen forever until the window is closed or the <code>clearInterval()</code> method is called.</p>
<p><strong id="clearInterval">clearInterval()</strong></p>
<p>The <code>clearInterval()</code> method can be used to stop the looped execution of a <code>setInterval()</code> method. It&#8217;s relatively simple to use and requires you to store the return of the <code>setInterval()</code> method into a variable:</p>
<pre class="brush: jscript; title: ; notranslate">
function theMethodToRepeat()
{
    // Do something
}

var the_interval = setInterval( 'theMethodToRepeat()', 5000 );

function stopTheInterval()
{
    the_interval = clearInterval( the_interval );
}
</pre>
<p>Whenever you wanted the loop to be stopped you could simply make a call to the <code>stopTheInterval()</code> function and it will clear the interval loop.</p>
<p><strong id="setTimeout">setTimeout()</strong></p>
<p>The <code>setTimeout()</code> method works almost identical to the <code>setInterval()</code> method except that it does not automatically loop over and over again. Instead, it waits the given amount of time and only executes the given code (typically a call to a function) once:</p>
<pre class="brush: jscript; title: ; notranslate">
function theMethodToCall()
{
    // Do something
}

setTimeout( 'theMethodToCall()', 5000 );
</pre>
<p>The above code will execute <code>theMethodToCall()</code> function after waiting five seconds. In order to use this in a loop you must include the <code>setTimeout()</code> method inside of the function it calls:</p>
<pre class="brush: jscript; title: ; notranslate">
function theMethodToCall()
{
    // Do something

    setTimeout( 'theMethodToCall()', 5000 );
}

theMethodToCall();
</pre>
<p>As you can see, <code>theMethodToCall()</code> function is executed over and over again, every five seconds. Just like the <code>setInterval()</code> method, the <code>setTimeout()</code> method can be canceled using the <code>clearTimeout</code> method.</p>
<p><strong id="clearTimeout">clearTimeout()</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var the_timeout;

function theMethodToCall()
{
    // Do something

    the_timeout = setTimeout( 'theMethodToCall()', 5000 );

    if ( someValue == true )
    {
        clearTimeout( the_timeout );
    }
}

theMethodToCall();
</pre>
<p>The code above checks if <code>someValue</code> equals <code>true</code>, and if it does then the <code>clearTimout()</code> method is called to make sure the loop is broken.</p>
<p><strong id="window.open">window.open()</strong></p>
<p>To be honest, I hardly ever use this method in my live production work, though I thought it was still worth describing. The <code>window.open()</code> method can be used to open a new browser window. It has four parameters which are all optional: the <abbr title="Uniform Resource Locator">URL</abbr>, the window name, the window specs, and a replace flag. If you use the method with no parameters it will simply open a blank window:</p>
<pre class="brush: jscript; title: ; notranslate">
window.open();
</pre>
<p>Specifying a <abbr title="Uniform Resource Locator">URL</abbr> and a window name is extremely straightforward:</p>
<pre class="brush: jscript; title: ; notranslate">
window.open( 'http://somedomain.com', 'The name of the new window' );
</pre>
<p>Passing in window specs is a bit more complex. You need to pass them as a comma separated list:</p>
<pre class="brush: jscript; title: ; notranslate">
window.open( 'http://somedomain.com', 'The name of the new window', 'width=800, height=600' );
</pre>
<p>There are many specs that you can define, though the most useful are the ones that are fully cross-browser compatible:</p>
<ul>
<li>width (window size, in pixels)</li>
<li>height (window size, in pixels)</li>
<li>left (window location, in pixels)</li>
<li>location (window has an address field, true or false / 0 or 1)</li>
<li>menubar (window has a menu bar, true or false / 0 or 1)</li>
<li>resizable (window is resizable, true or false / 0 or 1)</li>
<li>scrollbars (window has scrollbars, true or false / 0 or 1)</li>
<li>status (window has a status bar, true or false / 0 or 1)</li>
<li>titlebar (window has a title bar, true or false / 0 or 1)</li>
<li>toolbar (window has a tool bar, true or false / 0 or 1)</li>
</ul>
<p>Lastly, the replace parameter specifies whether the new window will add a new entry in the browser history or replace the current entry. This parameter should be set to <code>true</code> or <code>false</code>.</p>
<p>Now if you want to use <abbr title="Javascript">JS</abbr> to open a new window and write specific elements to it&#8217;s <abbr title="Document Object Model">DOM</abbr> then you&#8217;ll have the store the return of the <code>window.open()</code> method to a variable:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_new_window = window.open();
the_new_window.document.write( '&lt;p&gt;This is a paragraph tag in the new window!&lt;/p&gt;' );
the_new_window.focus();
</pre>
<p>This code is pretty self-explanatory and the only part we haven&#8217;t gone over is the <code>focus()</code> method which I will describe below. Keep in mind that using the <code>window.open()</code> method is pretty risky because many browser settings will detect this action as a pop-up window and block it from the user.</p>
<p><strong id="window.close">window.close()</strong></p>
<p>Using the <code>window.close()</code> method to close a window is pretty simple:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_new_window = window.open();
the_new_window.document.write( '&lt;p&gt;This is a paragraph tag in the new window!&lt;/p&gt;' );
the_new_window.focus();

function closeTheNewWindow()
{
    the_new_window.close();
}
</pre>
<p>As you can see in the code above we call the <code>close()</code> method on the appropriate variable (which stores the window reference) and we can close it quickly and easily.</p>
<p><strong id="window.focus">window.focus()</strong></p>
<p>In one example above I used the <code>focus()</code> method and I thought it would be wise to briefly explain that this method can be used to set which window has the current focus (which one is on top). It&#8217;s simple to use:</p>
<pre class="brush: jscript; title: ; notranslate">
some_window.focus();
</pre>
<p><strong id="window.blur">window.blur()</strong></p>
<p>And to compliment the <code>focus()</code> method is the <code>blur()</code> method, which does the exact opposite: removes the focus from the referenced window:</p>
<pre class="brush: jscript; title: ; notranslate">
some_window.blur();
</pre>
<p>There are many more methods and properties that belong to the <code>window</code> object, but I find that the above mentioned ones are the most essential for your native <abbr title="Javascript">JS</abbr> knowledge. I hope this short tutorial has been helpful for you beginners out there. Stay tuned for next week&#8217;s discipline: Navigator object browser detection.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a><br />
Discipline 3: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Include External JS</a><br />
Discipline 4: <a title="Native Javascript Ninjutsu: Cookie and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">Cookies and Variables</a><br />
Discipline 5: <a title="Native Javascript Ninjutsu: removeNode vs. removeChild" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/">removeNode vs. removeChild</a><br />
Discipline 6: <a title="Native Javascript Ninjutsu: DOMinating iframes" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/">DOMinating iframes</a><br />
Discipline 7: <a title="Native Javascript Ninjutsu: Document object methods &amp; properties" href="http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/">Document object methods &amp; properties</a></p>
<p><strong>Resources</strong><br />
<a title="Window Object" href="http://www.w3schools.com/jsref/obj_window.asp" target="_blank">W3Schools&#8217; HTML DOM Window Object</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-window-object-methods-properties/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: Document object methods &amp; properties</title>
		<link>http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/</link>
		<comments>http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/#comments</comments>
		<pubDate>Mon, 04 Oct 2010 08:00:50 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[document object]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[methods]]></category>
		<category><![CDATA[properties]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2453</guid>
		<description><![CDATA[Sensei Says (dark ages, to dojos, to disciplines) Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out. And then the frameworks came to rise: Dojo, Yahoo! UI Library, Google Web Toolkit, jQuery, Prototype, MooTools, and many more. With these [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 7: Chi-mon (geography)</strong></p>
<p class="note">NOTE: This article is for <abbr title="Javascript">JS</abbr> beginners only, and it will likely bore the rest of you!</p>
<p>While working with the <abbr title="HyperText Markup Language">HTML</abbr> <abbr title="Document Object Model">DOM</abbr> I find that it greatly helps to fully understand and know the <code>document</code> object itself. The <code>document</code> object mostly consists of three types of features: properties, methods, and objects of its own (though most of the objects are deprecated now). Here&#8217;s a quick list of what I plan to go over in this article:</p>
<p>Properties:</p>
<ul>
<li><a href="#document.cookie"><code>document.cookie</code></a></li>
<li><a href="#document.domain"><code>document.domain</code></a></li>
<li><a href="#document.referrer"><code>document.referrer</code></a></li>
<li><a href="#document.title"><code>document.title</code></a></li>
<li><a href="#document.URL"><code>document.URL</code></a></li>
</ul>
<p>Methods:</p>
<ul>
<li><a href="#document.createElement"><code>document.createElement</code></a></li>
<li><a href="#document.getElementById"><code>document.getElementById</code></a></li>
<li><a href="#document.getElementsByName"><code>document.getElementsByName</code></a></li>
<li><a href="#document.getElementsByTagName"><code>document.getElementsByTagName</code></a></li>
</ul>
<p>Let&#8217;s take a look at some of the most useful (and cross-browser compatible) properties first:</p>
<p><strong id="document.cookie">document.cookie</strong></p>
<p>I&#8217;ve already gone over this property at length in my <a title="Native Javascript Ninjutsu: Cookie and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">cookies and variables article</a> so I won&#8217;t go into much detail in this tutorial, but here&#8217;s a basic example:</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'cookie_name=cookie_value';
document.cookie = 'another_cookie_name=another_cookie_value';
document.write( document.cookie );
</pre>
<p>The above code will output &#8220;cookie_name=cookie_value; another_cookie_name=another_cookie_value&#8221;. As you can see the <code>document.cookie</code> property can be used to store a string of cookie names and values.</p>
<p><strong id="document.domain">document.domain</strong></p>
<p>The <code>domain</code> property returns the domain that loaded the current page. This property is read-only and cannot be set using <abbr title="Javascript">JS</abbr>.</p>
<pre class="brush: jscript; title: ; notranslate">
document.write( document.domain );
</pre>
<p>On this page the above code would output &#8220;blog.sociomantic.com&#8221;.</p>
<p><strong id="document.referrer">document.referrer</strong></p>
<p>The <code>referrer</code> property returns the <abbr title="Uniform Resource Locator">URL</abbr> of the page that loaded the current page. This property is read-only and cannot be set using <abbr title="Javascript">JS</abbr>.</p>
<pre class="brush: jscript; title: ; notranslate">
document.write( document.referrer );
</pre>
<p>On this page the above code could output &#8220;http://blog.sociomantic.com/&#8221; if you navigated to this article via our main blog page.</p>
<p><strong id="document.title">document.title</strong></p>
<p>The <code>title</code> property returns the <abbr title="Uniform Resource Locator">URL</abbr> of the current page. You can also set this property using <abbr title="Javascript">JS</abbr> to change the document <code>title</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
document.title = 'New Document Title';
</pre>
<p><strong id="document.URL">document.URL</strong></p>
<p>The <code>URL</code> property returns the <abbr title="Uniform Resource Locator">URL</abbr> of the current page. This property is read-only and cannot be set using <abbr title="Javascript">JS</abbr>.</p>
<pre class="brush: jscript; title: ; notranslate">
document.write( document.URL );
</pre>
<p>On this page the above code will output &#8220;http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-document-object-methods-properties/&#8221;.</p>
<p>There are many more properties that belong to the <code>document</code> object, though these are the ones that I find most useful in real-world applications. These are also the ones that I&#8217;ve found to be fully cross-browser compatible and <abbr title="Word Wide Web Consortium">W3C</abbr> compliant in my testing and research. Let&#8217;s continue our exploration of the <code>document</code> object by looking at a few of it&#8217;s most useful methods:</p>
<p><strong id="document.createElement">document.createElement()</strong></p>
<p>The <code>createElement()</code> method creates an <abbr title="HyperText Markup Language">HTML</abbr> element that can be added to the <abbr title="Document Object Model">DOM</abbr>. It&#8217;s pretty simple to use, you pass it the tag name of the element which you would like to create:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_element = document.createElement( 'p' );
</pre>
<p>The above code creates a <code>p</code> (paragraph) element, but does not yet add it to the page. Here&#8217;s an example of how to add the new element to the <abbr title="Document Object Model">DOM</abbr>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script id=&quot;the_script_id&quot; type=&quot;text/javascript&quot;&gt;
        var the_element = document.createElement( 'p' );
        var the_script = document.getElementById( 'the_script_id' );

        the_script.parentNode.insertBefore( the_element, the_script );
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>As you can see we store the new element in a variable, store another element in a variable, and use the location of the second element to help us place the first element into the page.</p>
<p><strong id="document.getElementById">document.getElementById()</strong></p>
<p>I&#8217;ve already demonstrated how to use the <code>getElementById()</code> above and I think that it&#8217;s very self-explanatory, but for those true beginners out there here&#8217;s the idea: you pass it an <code>id</code> value as the parameter and it returns the element (if found):</p>
<pre class="brush: jscript; title: ; notranslate">
var the_element = document.getElementById( 'some_id' );
</pre>
<p>Now let&#8217;s move onto two similar methods: <code>getElementsByName</code> and <code>getElementsByTagName</code>.</p>
<p><strong id="document.getElementsByName">document.getElementsByName()</strong></p>
<p>The <code>getElementsByName()</code> method is pretty self-explanatory: you pass it a <code>name</code> value as the parameter and it returns an array of all the elements that have the same value stored in their <code>name</code> attribute:</p>
<pre class="brush: jscript; title: ; notranslate">
var all_elements_with_some_name = document.getElementsByName( 'some_name' );
</pre>
<p>This is mostly used to count (or reference) the elements used in <abbr title="HyperText Markup Language">HTML</abbr> forms, particularly in the case of element groups that are required to share the same name (such as radio buttons or checkboxes).</p>
<p><strong id="document.getElementsByTagName">document.getElementsByTagName()</strong></p>
<p>The <code>getElementsByTagName</code> method is also pretty self-explanatory: you pass it a tag name as the parameter and it returns an array of all the elements that are of that tag type:</p>
<pre class="brush: jscript; title: ; notranslate">
var all_paragraphs = document.getElementsByTagName( 'p' );
</pre>
<p>There are many more methods and properties that belong to the <code>document</code> object, but I find that the above mentioned ones are the most essential for your native <abbr title="Javascript">JS</abbr> knowledge. I hope this short tutorial has been helpful for you beginners out there. Stay tuned for next week&#8217;s discipline: window &amp; location.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a><br />
Discipline 3: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Include External JS</a><br />
Discipline 4: <a title="Native Javascript Ninjutsu: Cookie and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">Cookies and Variables</a><br />
Discipline 5: <a title="Native Javascript Ninjutsu: removeNode vs. removeChild" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/">removeNode vs. removeChild</a><br />
Discipline 6: <a title="Native Javascript Ninjutsu: DOMinating iframes" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/">DOMinating iframes</a></p>
<p><strong>Resources</strong><br />
<a title="HTML DOM Document Object" href="http://www.w3schools.com/jsref/dom_obj_document.asp" target="_blank">W3Schools&#8217; HTML DOM Document Object</a><br />
<a title="Document Object" href="http://www.javascriptkit.com/jsref/document.shtml" target="_blank">Javascript Kit&#8217;s Document Object</a><br />
<a title="Document Object Methods" href="http://www.javascriptkit.com/domref/documentmethods.shtml" target="_blank">Javascript Kit&#8217;s Document Object Methods</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: DOMinating iframes</title>
		<link>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/</link>
		<comments>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/#comments</comments>
		<pubDate>Fri, 24 Sep 2010 14:44:23 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[cross-domain]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[fragment identifier]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[iframe]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2379</guid>
		<description><![CDATA[Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today's programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework?
Now that we've gone over some of the basics about using <code>iframes</code> it makes sense to discuss the relationship between the <code>iframe</code> and its <code>parent</code> page. When both your pages come from the same domain you can do a lot of simple communication between the <code>iframe</code> and the <code>parent</code> page. ]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 6: Bajutsu (horsemanship)</strong></p>
<p>I typically don&#8217;t front flip at the opportunity to use <code>iframes</code> in my native <abbr title="Javascript">JS</abbr> Ninjutsu practices, though I frequently find myself in the midst of a mission where I have no choice but to work with an <code>iframe</code>. While I may not need to approve of them, I certainly must make sure I know how to properly work with them in such cases. First and foremost, one must understand exactly what an <code>iframe</code> is, and I think it&#8217;s best to quote <a title="The HTML iframe element" href="http://en.wikipedia.org/wiki/HTML_element#Frames" target="_blank">Wikipedia&#8217;s iframe article</a>:</p>
<p><em>&#8220;An inline frame places another <abbr title="HyperText Markup Language">HTML</abbr> document in a frame. Unlike an object element, an inline frame can be the [<code>target</code>] frame for links defined by other elements and it can be selected by the user agent as the focus for printing, viewing its source etc. The content of the element is used as alternative text to be displayed if the browser does not support <code>iframes</code>. First introduced by [<abbr title="Microsoft Internet Explorer">MSIE</abbr>] in 1997, standardised in <abbr title="HyperText Markup Language">HTML</abbr> 4.0 Transitional, allowed in <abbr title="HyperText Markup Language">HTML</abbr> 5.&#8221;</em></p>
<p>Now that we understand what an <code>iframe</code> is, let&#8217;s learn how to add one to the <abbr title="HyperText Markup Language">HTML</abbr> <abbr title="Document Object Model">DOM</abbr>:</p>
<pre class="brush: jscript; title: ; notranslate">
document.write( '&lt;/pre&gt;
&lt;iframe width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;' );
</pre>
<p>That is the quickest and simplest way to get an <code>iframe</code> written to the <abbr title="Document Object Model">DOM</abbr>, though of course, if you want to be able to manipulate it further with <abbr title="Javascript">JS</abbr> it would make sense to give it an <code>id</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
document.write( '&lt;/pre&gt;
&lt;iframe id=&quot;the_iframe_id&quot; width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;' );
</pre>
<p>Alternatively you can give the <code>iframe</code> a <code>name</code> value and access it using the <code>window.frames</code> array (which I will demonstrate later in the article). The advantage to this approach is that it seems to be more backward compatible with older (legacy) web browsers:</p>
<pre class="brush: jscript; title: ; notranslate">
document.write( '&lt;/pre&gt;
&lt;iframe name=&quot;the_iframe_name&quot; width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;' );
</pre>
<p>Despite it&#8217;s one-line appeal, the <code>document.write</code> method has a major downside: the <abbr title="Javascript">JS</abbr> itself must be located in the exact place in the <abbr title="Document Object Model">DOM</abbr> that you want the <code>iframe</code> to be inserted. For this reason I typically use the <code>document.createElement</code> and <code>parentNode.insertBefore</code> approach:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_iframe = document.createElement( 'iframe' );
the_iframe.id = 'the_iframe_id';

var another_element = document.getElementById( 'another_element_id' );
another_element.parentNode.insertBefore( the_iframe, another_elment.nextSibling );
</pre>
<p>The above code will create the <code>iframe</code>, give it an <code>id</code> value, locate another specific element on the page (which you want to insert the <code>iframe</code> after), and then add the new <code>iframe</code> to the <abbr title="Document Object Model">DOM</abbr> at the given location.</p>
<p>Adding the <code>iframe</code> won&#8217;t do much though, as we need to give it a <code>src</code> value before any content will appear inside of it:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_iframe = document.createElement( 'iframe' );
the_iframe.id = the_'iframe_id';
the_iframe.src = 'http://domain.com/directory/filename.html';

var another_element = document.getElementById( 'another_element_id' );
another_element.parentNode.insertBefore( the_iframe, another_elment.nextSibling );
</pre>
<p>Changing the content of the <code>iframe</code> is as easy as changing the value of the <code>src</code> attribute:</p>
<pre class="brush: jscript; title: ; notranslate">
document.getElementById( 'the_iframe_id' ).src = 'http://new-domain.com/new-directory/new-filename.html';
</pre>
<p>As I mentioned above, you may use the legacy approach that relies on the <code>iframe</code> having a <code>name</code> value:</p>
<pre class="brush: jscript; title: ; notranslate">
window.frames[ 'the_iframe_name' ].location = 'http://new-domain.com/new-directory/new-filename.html';
</pre>
<p>Although it&#8217;s nice to understand legacy and alternative approaches, this one in particular does not seem to be all that useful. In my cross-browser tests the <code>document.getElementById().src</code> method works in all eighteen (18) web browsers that I routinely check (<abbr title="Microsoft Internet Explorer 9 (preview)">IE9</abbr>, <abbr title="Microsoft Internet Explorer 8">IE8</abbr>, <abbr title="Microsoft Internet Explorer 7">IE7</abbr>, <abbr title="Microsoft Internet Explorer 6">IE6</abbr>, <abbr title="Firefox 4 (beta)">FF4</abbr>, <abbr title="Firefox 3.6">FF3.6</abbr>, <abbr title="Firefox 3.5">FF3.5</abbr>, <abbr title="Firefox 3">FF3</abbr>, <abbr title="Firefox 2">FF2</abbr>, <abbr title="Google Chrome 7">GC7</abbr>, <abbr title="Google Chrome 6 (beta)">GC6</abbr>, <abbr title="Google Chrome 5">GC5</abbr>, <abbr title="Google Chrome 4">GC4</abbr>, <abbr title="Apple Safari 5">Safari 5</abbr>, <abbr title="Apple Safari 4">Safari 4</abbr>, <abbr title="Apple Safari 3">Safari 3</abbr>, Opera 10, and Opera 9). In my opinion this would mean that it&#8217;s a cross-browser compatible solution that is safe to use for all purposes.</p>
<p>Now that we&#8217;ve gone over some of the basics about using <code>iframes</code> it makes sense to discuss the relationship between the <code>iframe</code> and its <code>parent</code> page. When both your pages come from the same domain you can do a lot of simple communication between the <code>iframe</code> and the <code>parent</code> page. There are three different ways you can reference the <code>iframe</code>&#8216;s content:</p>
<ol>
<li>using the <code>document.getElementById( 'the_iframe_id' ).contentDocument</code> method,</li>
<li>using the <code>document.getElementById( 'the_iframe_id' ).contentWindow.document</code> method,</li>
<li>or using the <code>window.frames[ 'the_iframe_name' ].document</code> method.</li>
</ol>
<p>I&#8217;ve done some extensive cross-browser testing and it seems that out of my usual eighteen (18) web browsers (listed above) the only two that don&#8217;t support the <code>contentDocument</code> method are <abbr title="Microsoft Internet Explorer 6">IE6 and <abbr title="Microsoft Internet Explorer 7">IE7. For this reason I would to one of the following:</abbr></abbr></p>
<ul>
<li>Stick to using only <code>contentWindow</code></li>
</ul>
<pre class="brush: jscript; title: ; notranslate">
var the_iframe = document.getElementById( 'the_iframe_id' );
var some_element = the_iframe.contentWindow.document.getElementById( 'some_element_id' );
</pre>
<ul>
<li>or check to see if <code>contentDocument</code> is available before using it)</li>
</ul>
<pre class="brush: jscript; title: ; notranslate">
var the_iframe = document.getElementById( 'the_iframe_id' );

if ( the_iframe.contentDocument )
{
    var some_element = the_iframe.contentDocument.getElementById( 'some_element_id' );
}
else if ( the_iframe.contentWindow )
{
    var some_element = the_iframe.contentWindow.document.getElementById( 'some_element_id' );
}
</pre>
<p>There is one more alternative method to both of the above, and that is to rely on the <code>name</code> attribute of the <code>iframe</code> and access its elements using the <code>window.frames</code> array:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_iframe = window.frames[ 'the_iframe_name' ];
var some_element = the_iframe.document.getElementById( 'some_element_id' );
</pre>
<p>This last method is (again) more suitable for legacy web browsers, though it does appear to work in all the modern web browsers that I typically test for cross-browser compatibility. Let&#8217;s put this all together in the following example which shows you how to communicate down (from the <code>parent</code> page to the <code>iframe</code>):</p>
<pre class="brush: xml; title: ; notranslate">

&lt;/pre&gt;
&lt;iframe id=&quot;the_iframe_id&quot; src=&quot;the_iframe_content.html&quot; width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
        function removeSomeElement()
        {
            var the_iframe = document.getElementById( 'the_iframe_id' );

            if ( the_iframe.contentDocument )
            {
                var some_element = the_iframe.contentDocument.getElementById( 'some_element_id' );
            }
            else if ( the_iframe.contentWindow )
            {
                var some_element = the_iframe.contentWindow.document.getElementById( 'some_element_id' );
            }

            some_element.parentNode.removeChild( some_element );
        };

// ]]&gt;&lt;/script&gt;
</pre>
<p>And here is the source code of <code>the_iframe_content.html</code>:</p>
<pre class="brush: xml; title: ; notranslate">

This element should not be visible

This element should be visible
</pre>
<p>As you can see above I use the <code>onload</code> attribute/event to make sure the <code>iframe</code> has fully loaded it&#8217;s source before allowing the <code>removeSomeElement()</code> function to be executed. If I didn&#8217;t do this it&#8217;s very likely that <code>the_iframe</code> variable would end up being set as <code>null</code> or <code>undefined</code> and then the following code wouldn&#8217;t be able to properly locate the target element.</p>
<p>This whole process is referred to as &#8216;referencing down&#8217; (or &#8216;communicating down&#8217;) because you are going from the <code>parent</code> page down into its child <code>iframe</code>. Similarly, &#8216;referencing up&#8217; is when you reference the <code>iframe</code>&#8216;s <code>parent</code> (and its <abbr title="Document Object Model">DOM</abbr> elements) by using the <code>parent.document</code> method:</p>
<pre class="brush: jscript; title: ; notranslate">
var some_parent_element = parent.document.getElementById( 'some_parent_element_id' );
</pre>
<p>Here&#8217;s how to add this method into our previous example:</p>
<pre class="brush: xml; title: ; notranslate">

This element should not be visible

This element should be visible

&lt;/pre&gt;
&lt;iframe id=&quot;the_iframe_id&quot; src=&quot;the_iframe_content.html&quot; width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
        function removeSomeElement()
        {
            var the_iframe = document.getElementById( 'the_iframe_id' );

            if ( the_iframe.contentDocument )
            {
                var some_element = the_iframe.contentDocument.getElementById( 'some_element_id' );
            }
            else if ( the_iframe.contentWindow )
            {
                var some_element = the_iframe.contentWindow.document.getElementById( 'some_element_id' );
            }

            some_element.parentNode.removeChild( some_element );
        };

// ]]&gt;&lt;/script&gt;
</pre>
<p>And here is the source code of <code>the_iframe_content.html</code>:</p>
<pre class="brush: xml; title: ; notranslate">

This element should not be visible

This element should be visible

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
        var the_parent_element = parent.document.getElementById( 'some_parent_element_id' );

        the_parent_element.parentNode.removeChild( the_parent_element );

// ]]&gt;&lt;/script&gt;
</pre>
<p>If everything works right each targeted element should be removed from its respective <code>parent</code> page&#8217;s <abbr title="Document Object Model">DOM</abbr>. The cool part of this feature is that you can easily use the same methods to deal with nested <code>iframes</code>. You can reference an <code>iframe</code> element two levels down by doing the following:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_first_iframe = document.getElementById( 'the_first_iframe_id' );
var the_second_iframe = the_iframe.contentWindow.document.getElementById( 'the_second_iframe_id' );
var some_element = the_second_iframe.contentWindow.document.getElementById( 'some_element_id' );
</pre>
<p>Similarly, to reference an element in the top level <code>parent</code> of an <code>iframe</code> you can do the following:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_top_parent_element = parent.parent.document.getElementById( 'the_top_parent_element_id' );
</pre>
<p>In theory you should be able to repeat this infinitely, though I&#8217;m sure there are <code>iframe</code> limits imposed by web browsers as a basic safety measure (I have not needed to test this before but maybe I will as it sounds interesting enough).</p>
<p>So far so good, but as soon as you begin playing with cross-domain <code>src</code> values in your <code>iframe</code> you&#8217;ll notice that communication between the <code>parent</code> and the <code>iframe</code> becomes extremely restricted. If the <code>parent</code> page and the <code>iframe</code> <code>src</code> are from two separate domains then it will be impossible to directly access the <abbr title="Document Object Model">DOM</abbr> elements of one from the <abbr title="Javascript">JS</abbr> of the other. However there is a technique (more suitably referred to as a &#8216;hack&#8217;) that uses fragment identifiers to pass information cross-domain between an <code>iframe</code> and it&#8217;s <code>parent</code>. A fragment identifier is the part of the <abbr title="Uniform Resource Locator">URL</abbr> that follows the hash / anchor symbol (#). If you change (or add) this value it will not reload or refresh the page, but it does modify the <code>window.location.hash</code> value. The trick is to constantly measure the <code>window.location.hash</code> every second (or so) to see if the value has changed. This technique is called &#8216;polling&#8217;. Here&#8217;s a working example of the fragment (hash) identifier and polling techniques used to reference down in a cross-domain environment:</p>
<pre class="brush: xml; title: ; notranslate">

&lt;/pre&gt;
&lt;form id=&quot;the_form_id&quot;&gt;&lt;input id=&quot;the_input_id&quot; type=&quot;text&quot; value=&quot;black&quot; /&gt;
 &lt;button id=&quot;the_submit_id&quot; type=&quot;submit&quot;&gt;reference down&lt;/button&gt;&lt;/form&gt;
&lt;pre&gt;
&lt;/pre&gt;
&lt;iframe id=&quot;the_iframe_id&quot; src=&quot;http://someotherdomain.com/the_iframe_content.html&quot; width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
        function setupTheForm()
        {
            var the_iframe = document.getElementById( 'the_iframe_id' );
            var the_form = document.getElementById( 'the_form_id' );
            var the_input = document.getElementById( 'the_input_id' );
            var the_src = 'http://someotherdomain.com/the_iframe_content.html#';

            the_form.onsubmit = function ()
            {
                var the_value = the_input.value;
                the_iframe.src = the_src + the_value;

                return false;
            }
        };

// ]]&gt;&lt;/script&gt;
</pre>
<p>And here is the source code of <code>the_iframe_content.html</code> (which should be located on a separate domain):</p>
<pre class="brush: xml; title: ; notranslate">

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
        var poll;

        function startPolling ()
        {
            var the_hash_value = window.location.hash.substr( 1 );
            document.body.style.backgroundColor = the_hash_value;
            poll = setTimeout( 'startPolling()', 1000 );
        }

// ]]&gt;&lt;/script&gt;
</pre>
<p>Most of the above code should be pretty self-explanatory, but I&#8217;ll go into a bit of detail for those readers who are less familiar with native <abbr title="Javascript">JS</abbr>. First we apply an <code>onload</code> event to the <code>body</code> of our <code>parent</code> page and set this event to trigger the <code>setupTheForm()</code> function. This function stores the <code>iframe</code> element, the <code>form</code> element, the <code>input</code> element, and the <code>iframe</code> <code>src</code> value into their own variables. Notice that <code>the_src</code> variable includes the original <code>iframe</code> content <abbr title="Uniform Resource Locator">URL</abbr> with a hash symbol added to the end. This is necessary to make sure the fragment identifier is parsed correctly and also doesn&#8217;t refresh or reload the content within the <code>iframe</code>. Next we add a custom function to the <code>onsubmit</code> event of the <code>form</code> which stores the <code>value</code> of the <code>input</code> element, combines it with <code>the_src</code> variable, and uses the result to update the <code>iframe</code> <code>src</code> attribute. The function will also <code>return false</code> in order to prevent the default <abbr title="HyperText Markup Language">HTML</abbr> <code>form</code> submit event from being triggered (in case there is one).</p>
<p>The <code>iframe</code> content also has an <code>onload</code> event that triggers the <code>startPolling()</code> function. This function grabs the fragment identifier by using the <code>window.location.hash</code> method. We also apply the <code>substr()</code> method to remove the first character of the hash string (which will always be the hash symbol). In this example we&#8217;re assuming that the user will always provide a value that is equal to one of the <abbr title="HyperText Markup Language">HTML</abbr> colors (such as white, black, blue, green, yellow, orange, red, purple, etc) and we use this value to set the <code>document.body.style.backgroundColor</code>. Lastly, the function references the global <code>poll</code> variable, storing <code>setTimeout()</code> to it, which waits for the given time in milliseconds (the second parameter) before calling the provided function (the first parameter). Since this <code>setTimeout</code> always calls it&#8217;s parent function it will repeat the function infinitely, thus providing us with a working polling mechanism.</p>
<p>Now that you&#8217;ve seen how to reference down in a cross-domain environment, let&#8217;s complete the test by incorporating the code needed to reference up as well:</p>
<pre class="brush: xml; title: ; notranslate">

&lt;/pre&gt;
&lt;form id=&quot;the_form_id&quot;&gt;&lt;input id=&quot;the_input_id&quot; type=&quot;text&quot; value=&quot;black&quot; /&gt;
 &lt;button id=&quot;the_submit_id&quot; type=&quot;submit&quot;&gt;reference down&lt;/button&gt;&lt;/form&gt;
&lt;pre&gt;
&lt;/pre&gt;
&lt;iframe id=&quot;the_iframe_id&quot; src=&quot;http://someotherdomain.com/the_iframe_content.html&quot; width=&quot;320&quot; height=&quot;240&quot;&gt;&lt;/iframe&gt;
&lt;pre&gt;

&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
    var poll;

    function startPolling ()
    {
        var the_hash_value = window.location.hash.substr( 1 );
            document.body.style.backgroundColor = the_hash_value;
        poll = setTimeout( 'startPolling()', 1000 );
        }

        function setupTheForm()
        {
            var the_iframe = document.getElementById( 'the_iframe_id' );
            var the_form = document.getElementById( 'the_form_id' );
            var the_input = document.getElementById( 'the_input_id' );
            var the_src = 'http://someotherdomain.com/the_iframe_content.html#';

            the_form.onsubmit = function ()
            {
                var the_value = the_input.value;
                the_iframe.src = the_src + the_value;

                return false;
            }

            startPolling();
        };

// ]]&gt;&lt;/script&gt;
</pre>
<p>And here is the source code of <code>the_iframe_content.html</code> (which should be located on a separate domain):</p>
<pre class="brush: xml; title: ; notranslate">

&lt;/pre&gt;
&lt;form id=&quot;the_form_id&quot;&gt;&lt;input id=&quot;the_input_id&quot; type=&quot;text&quot; value=&quot;black&quot; /&gt;
 &lt;button id=&quot;the_submit_id&quot; type=&quot;submit&quot;&gt;reference up&lt;/button&gt;&lt;/form&gt;
&lt;pre&gt;
&lt;script type=&quot;text/javascript&quot;&gt;// &lt;![CDATA[
        var poll;

        function startPolling ()
        {
            var the_hash_value = window.location.hash.substr( 1 );
            document.body.style.backgroundColor = the_hash_value;
            poll = setTimeout( 'startPolling()', 1000 );
        }

        function setupTheForm ()
        {
            var the_form = document.getElementById( 'the_form_id' );
            var the_input = document.getElementById( 'the_input_id' );

            the_form.onsubmit = function ()
            {
                var the_value = the_input.value;
                parent.window.location.hash = the_value;

                return false;
            }
        }

// ]]&gt;&lt;/script&gt;
</pre>
<p>For this example you&#8217;ll notice that the <code>parent</code> page content and the <code>iframe</code> content are almost identical. The main difference is that the <code>iframe</code> will not need to store values for <code>the_iframe</code> and <code>the_src</code> variables, and that when the <code>form</code> <code>onsubmit</code> event is triggered the <abbr title="Javascript">JS</abbr> will store <code>the_value</code> into the <code>parent</code> page&#8217;s fragment identifier by using the <code>parent.window.location.hash</code> method. While the first example (referencing down) was fully cross-browser compatible (at least concerning the eighteen web browsers I&#8217;ve mentioned earlier in the article), the second example appears to only work in Firefox. This has to do with the various browser limitations imposed on setting the <code>parent.window.location.hash</code> value. It appears that this line of code can be replaced with <code>parent.location</code> though you&#8217;ll have to add the whole <abbr title="Uniform Resource Locator">URL</abbr> with the hash value and this means the <code>parent</code> page could possibly be refreshed/reloaded (I did not do extensive testing to verify whether the <code>parent</code> page is actually reloaded or not in every browser). Also, it&#8217;s important to remember that you&#8217;ll be restricted by any size restraints which apply to the <abbr title="Uniform Resource Locator">URL</abbr> itself. For this reason the fragment identifier method is obviously limited to passing smaller bits of information between the <code>parent</code> page and its children.</p>
<p>This article is far from covering all the aspects of the <code>iframe</code> and how it works &#8211; especially in cross-domain environments &#8211; but I hope it has been a helpful tutorial, providing you with a way to use native <abbr title="Javascript">JS</abbr> to work with <code>iframes</code>. Stay tuned for next week&#8217;s discipline: <a title="Native Javascript Ninjutsu: Document object methods &amp; properties" href="http://blog.sociomantic.com/2010/10/native-javascript-ninjutsu-document-object-methods-properties/">Document object methods &amp; properties</a>.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a><br />
Discipline 3: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Include External JS</a><br />
Discipline 4: <a title="Native Javascript Ninjutsu: Cookie and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">Cookies and Variables</a><br />
Discipline 5: <a title="Native Javascript Ninjutsu: removeNode vs. removeChild" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/">removeNode vs. removeChild</a></p>
<p><strong>Resources</strong><br />
<a title="Scripting Iframes - Tutorial and Examples" href="http://www.dyn-web.com/tutorials/iframes/" target="_blank">Dynamic Web Coding&#8217;s iframe scripting tutorial</a><br />
<a title="Cross-Domain Communication with IFrames" href="http://softwareas.com/cross-domain-communication-with-iframes" target="_blank">Software As She&#8217;s Developed&#8217;s Cross Domain iframe article</a><br />
<a title="Tagneto: Cross Domain Frame Communication with Fragment Identifiers (for Comet?)'" href="http://tagneto.blogspot.com/2006/06/cross-domain-frame-communication-with.html" target="_blank">Tagneto&#8217;s Cross Domain Frame Communication with Fragment Identifiers</a><br />
<a title="Cross-Domain Comms via IFrame Demo" href="http://ajaxify.com/run/crossframe/" target="_blank">AJAXPatterns&#8217; Cross-Domain Comms via IFrame Demo</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-dominating-iframes/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Implementing an asynchronous, epoll based network client with Tango on Linux</title>
		<link>http://blog.sociomantic.com/2010/09/implementing-an-asynchronous-epoll-based-network-client-with-tango-on-linux/</link>
		<comments>http://blog.sociomantic.com/2010/09/implementing-an-asynchronous-epoll-based-network-client-with-tango-on-linux/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 16:29:23 +0000</pubDate>
		<dc:creator>David</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[D language]]></category>
		<category><![CDATA[epoll]]></category>
		<category><![CDATA[linux]]></category>
		<category><![CDATA[non-blocking I/O]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[tango]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2311</guid>
		<description><![CDATA[A way that provides much better performance for a big number of simultaneously handled socket connections than starting a handler thread for each connection is to handle all connections in the main thread, using Linux’ epoll interface in combination with non-blocking socket I/O. Tango’s EpollSelector is built on top of epoll and provides a pretty good D interface for it.]]></description>
			<content:encoded><![CDATA[<p style="text-align: center;"><img class="aligncenter  wp-image-2347" title="11971024951537266953FunDraw_dot_com_Coloring_Book_Octopus.svg.hi" src="http://blog.sociomantic.com/wp-content/uploads/11971024951537266953FunDraw_dot_com_Coloring_Book_Octopus.svg_.hi_.png" alt="Octopus illustration" /></p>
<p><strong>Implementing an asynchronous, epoll based network client with Tango on Linux</strong></p>
<p class="note">NOTE: The code snippets in this article use the D brush extension we built for the SyntaxHighlighter Evolved WP plugin. Info &amp; download <a href="http://www.sociomantic.com/resources/our-projects/wordpress-plugin-extension-syntaxhighlighter-evolved-d-brush/" target="_blank">here.</a></p>
<p>To implement a network client application which can handle multiple socket connections simultaneously, there are basically two approaches:</p>
<ol>
<li>using threads and handling each connection with an own thread,</li>
<li>having multiple connection session contexts and handling all connections with a single thread.</li>
</ol>
<p>Approach 1 is pretty straight forward. Consider a simple case where the client application sends request data to the server and then receives response data from the server. The following code starts five client threads. Each thread connects to server <code>localhost</code>, port 4711, writes <code>request_data</code> (whatever it is) and reads <code>response_data</code> (whatever that is).</p>
<pre class="brush: d; title: ; notranslate">
module ThreadedClient;

import tango.net.device.Socket;
import tango.core.Thread;

void main ( )
{
    Thread[5] threads;                  // 5 threads

    foreach (ref thread; threads)       // create thread instances
    {
        thread = new Thread(&amp;doRequest);
    }

    foreach (thread; threads)           // start threads
    {
        thread.start();
    }

    foreach (thread; threads)           // wait for all threads to
    {                                   // finish
        thread.join();
    }
}

void doRequest ( )
{
    scope socket = new Socket;          // create socket
                                        // connection

    socket.connect(&quot;localhost&quot;, 4711);  // connect to server

    void[] request_data;                // request data buffer
    socket.write(request_data);         // send request

    void[] response_data;               // response data buffer
    response_data.length = 10;          // response will have a
                                        // length of 10 bytes

    socket.read(response_data);         // receive response
}
</pre>
<p class="note">Note: For sake of simplicity, we assume that <code>socket.write()</code> sends all provided data and <code>socket.read()</code> completely populates the provided buffer. Since one cannot rely on that, it is advisable to wrap <code>socket.write()</code>/<code>socket.read()</code> in a loop or use Tango&#8217;s <a href="http://dsource.org/projects/tango/docs/stable/tango.io.stream.Buffered.html"> <code>BufferedInput</code>/<code>BufferedOutput</code></a>.</p>
<p>The threading approach works fine with a few (up to about 20) connections but scales badly because each thread has a significant resource usage overhead. A way that provides much better performance for a big number of simultaneously handled connections is to handle all connections in the main thread, using Linux&#8217; <code>epoll</code> interface in combination with non-blocking socket I/O.</p>
<p>Tango&#8217;s <a href="http://dsource.org/projects/tango/docs/stable/tango.io.selector.EpollSelector.html"><code>EpollSelector</code></a> is built on top of <a href="http://www.kernel.org/doc/man-pages/online/pages/man4/epoll.4.html"><code>epoll</code></a> and provides a pretty good <abbr title="D (programming language)">D</abbr> interface for it. These are the steps to use the <code>EpollSelector</code> with multiple sockets:</p>
<ol>
<li>Create an <code>EpollSelector</code> instance and several <code>Socket</code> instances.</li>
<li>Set the <code>Sockets</code> to non-blocking I/O and connect to the server.</li>
<li>Register each of the <code>Socket</code> instances in the <code>EpollSelector</code> instance for an event. The event is usually <code>Write</code> (&#8220;socket became ready for writing&#8221;) or <code>Read</code> (&#8220;data arrived at socket so it became ready to read&#8221;).</li>
<li>Let the <code>EpollSelector</code> instance wait for an event to happen on some of the sockets.</li>
<li>Query which event actally happened on which socket by retrieving and iterating over the so-called <em>Selection Keys</em> from the <code>EpollSelector</code>.</li>
<li>Write to or read from the socket(s) which became ready to write/read and watch the return value of <code>write()</code>/<code>read()</code> to see how much of the data passed to <code>write()</code> have actually been written or, respectively, how much of the data buffer passed to <code>read()</code> has actually been populated.</li>
<li>If comparison of the read/write buffer length to the <code>read()</code>/<code>write()</code> return value indicates that there is more data to send or receive, continue with step 4.</li>
<li>Unregister the socket from the <code>EpollSelector</code>.</li>
<li>If you want to perform another read or write, continue with step 3.</li>
<li>Finished!</li>
</ol>
<p>The following example demonstrates how to use an <code>EpollSelector</code> to wait for our five sockets to become ready to write, following step 1 to 5.</p>
<pre class="brush: d; title: ; notranslate">
module ThreadedClient;

import tango.net.device.Socket;
import tango.io.selector.EpollSelector;
import tango.io.selector.model.ISelector : Event;

import tango.time.Time: TimeSpan;

void main ( )
{
    /*
     * Step 1: Create an EpollSelector and the Socket instances
     */
    scope selector = new EpollSelector;

    Socket[5] sockets;

    foreach (ref socket; sockets)
    {
        socket = new Socket;
    }

    /*
     * Step 2: Set the sockets to non-blocking I/O and connect to
     * the server
     */
    foreach (socket; sockets)
    {
        socket.socket.blocking = false;
        socket.connect(&quot;localhost&quot;, 4711);
    }

    /*
     * Step 3: Register each of the Socket instances in the
     * EpollSelector instance for an event. Here we register all
     * sockets for the event &quot;socket became ready to for writing&quot;.
     */
    foreach (socket; sockets)
    {
        selector.register(socket, Event.Write);
    }

    /*
     * Step 4: Let the EpollSelector instance wait for an event to
     * happen on some of the sockets. We have to provide a
     * TimeSpan timeout parameter; TimeSpan.max disables timing
     * out.
     */
    selector.select(TimeSpan.max);

   /* Step 5: Query which event actally happened on which socket
    * by retrieving and iterating over the Selection Keys from the
    * EpollSelector instance.
    * Note that EpollSelector.selectedSet may be null.
    */

    auto selection_set = selector.selectedSet;

    if (selection_set) foreach (selection_key; selection_set)
    {
        // - selection_key.conduit is one of our sockets which
        //      just became ready for writing;
        // - selection_key.events contains the events that
        //      happened on the socket. We expect Event.Write but
        //      it may also be an error event like Event.Error,
        //      Event.InvalidHandle or Event.Hangup.
        //      Event.Hangup would notify us that the server
        //      closed the socket connection.

        /*
         * TODO -- Step 6: Write to or read from the socket(s)
         * would go here...
         */
    }
}
</pre>
<p>Now that we know how to wait for and be notified about each socket&#8217;s I/O readiness, we can start writing our request data into each socket. Here the mechanism of non-blocking I/O gets important.</p>
<p>Consider the following example of the Selection Key iteration body:</p>
<pre class="brush: d; title: ; notranslate">
    foreach (selection_key; selector)
    {
        /*
         * Step 6: Write to or read from the socket(s). (In the
         * real world we would check selection_key.events for an
         * error event before doing anything.)
         */

        Socket socket = cast (Socket) selection_key.conduit;

        socket.write(&quot;Hello World!&quot;);
    }
</pre>
<p>There is always the possibility that the socket cannot instantly send all provided data. Usually <code>socket.write()</code> could then block and wait until the remaining data can be sent. Or imagine we would read from the socket, not all data we expect could have arrived which is very likely when we want to receive significantly more than just a <code>Hello World!</code> string.</p>
<p>To handle all connections as quickly as possible, we set the socket to <code>non-blocking</code>. That means that <code>socket.write()</code>/<code>read()</code> consume or produce just as many data as possible right now and return the number of bytes actually consumed or produced. Then we iterate over the Selection Keys, call <code>socket.write()</code> passing all output data to be written to this socket and memorize the return value which tells us how much of the data the socket actually consumed.</p>
<p>When the Selection Key iteration loop is finished, all of our sockets are busy sending the data they consumed. Then we call <code>select()</code> again to wait until a socket gets ready for writing and run the Selection Key iteration loop again to send the pending data.</p>
<p>That all is nice and good but the following difficulty arises from it. For each socket, we need:</p>
<ul>
<li>a separate output buffer because in general the socket connections get different output data,</li>
<li>a counter that memorizes how much of the output data have actually been written into this socket.</li>
</ul>
<p>That&#8217;s easy so far, we say, so for five sockets we just create five <code>void[]</code> buffer and five int counter variables. But when we are inside the Selection Key iteration loop, how do we know which buffer and counter belongs to the socket of the current Selection Key?</p>
<p>Fortunately, <code>epoll</code>, and so the <code>EpollSelector</code>, provide a pretty clever solution for this problem, the so-called Selection Key <em>attachment</em>. <code>EpollSelector.register()</code> accepts an optional third parameter of type <code>Object</code> &#8212; an arbitrary class instance &#8211;, which is attached to the registered conduit. Inside the Selection Key iteration loop the <code>SelectionKey.attachment</code> property contains the object attached to <code>SelectionKey.conduit</code>.</p>
<p>So we have to create a class that contains the context of each socket connection, in our example the output buffer and byte counter. Putting it all together, the code example expands to:</p>
<pre class="brush: d; title: ; notranslate">
module ThreadedClient;

import tango.net.device.Socket;
import tango.io.selector.EpollSelector;
import tango.io.selector.model.ISelector : Event;

import tango.time.Time: TimeSpan;

import tango.text.convert.Format;

/*
 * Socket item class, bundles a socket instance with its event to
 * be registered for and its context.
 */
class SocketItem
{
    /*
     * Socket context class, used for the socket attachment
     */
    static class Context
    {
        size_t counter = 0;
        void[] data;
    }

    /*
     * Socket instance
     */
    Socket  socket;

    /*
     * Event to register the bundled socket for
     */
    Event   event;

    /*
     * Context attachment for the bundled socket
     */
    Context context;

    /*
     * Constructor
     */
    this ( )
    {
        this.socket  = new Socket;
        this.context = new Context;
    }
}

/*
 * main method
 */

void main ( )
{
    /*
     * Step 1: Create an EpollSelector and the Socket instances
     */
    scope selector = new EpollSelector;

    SocketItem[5] sockitems;

    foreach (ref sockitem; sockitems)
    {
        sockitem = new SocketItem;
    }

    /*
     * Step 2: Set the sockets to non-blocking I/O and connect to
     * the server. Here we also define the event and output data.
     */
    foreach (i, sockitem; sockitems)
    {
        sockitem.socket.socket.blocking = false;
        sockitem.socket.connect(&quot;localhost&quot;, 4711);

        sockitem.event = sockitem.event.Write;

        sockitem.context.data = Format(&quot;Hello World from Socket &quot;
                                       &quot;{}!&quot;, i + 1).dup;
    }

    /*
     * Step 3: Register each of the Socket instances in the
     * EpollSelector instance for an event. Here we register the
     * socket with the bundled event and context attachment of
     * each sockitems element.
     */
    foreach (sockitem; sockitems)
    {
        selector.register(sockitem.socket, sockitem.event,
                          sockitem.context);
    }

    do
    {
        /*
         * Step 4: Let the EpollSelector instance wait for an
         * event to happen on some of the sockets. We have to
         * provide a TimeSpan timeout parameter; TimeSpan.max
         * disables timing out.
         */
        selector.select(TimeSpan.max);

       /* Step 5: Query which event actally happened on which
        * socket by retrieving and iterating over the Selection
        * Keys from the EpollSelector instance.
        * Note that EpollSelector.selectedSet may be null.
        */

        auto selection_set = selector.selectedSet;

        if (selection_set) foreach (selection_key; selection_set)
        {
            // - selection_key.conduit is one of our sockets which
            //      just became ready for writing;
            // - selection_key.events contains the events that
            //      happened on the socket. We expect Event.Write
            //      but it may also be an error event like
            //      Event.Error, Event.InvalidHandle or
            //      Event.Hangup.
            //      Event.Hangup would notify us that the server
            //      closed the socket connection.

            /*
             * Step 6: Write to or read from the socket(s). (In
             * the real world we would check selection_key.events
             * for an error event before doing anything.)
             */

            Socket socket = cast (Socket) selection_key.conduit;

            // Retrieve the socket connection context.

            SocketItem.Context context =
                cast(SocketItem.Context) selection_key.attachment;

            // Attempt to write all pending data and increase the
            // counter by the number of bytes actually written.
            // (In the real world we would first check if the
            // return value of write() is socket.Eof.)

            context.counter +=
                socket.write(context.data[context.counter .. $]);
        }
    }
    /*
     * TODO -- Steps 7 and 8: Unregister sockets whose counter
     * reached context.data.length from the selector and let this
     * loop stop when all sockets are unregistered.
     */
    while (true)
}
</pre>
<p>A loop which waits for events to happen and then handles these events, as the <code>while</code> loop in the example does, is often called an <em>Event Loop</em>.</p>
<p>Finally we have to unregister the sockets which are finished writing and terminate the event loop when no more socket is registered. Since <code>EpollSelector.count()</code> returns the number of registered conduits, we can just use this value as the loop condition.</p>
<pre class="brush: d; title: ; notranslate">
     /*
     * Step 7 (moved to front): Let the event loop stop when all
     * sockets are unregistered.
     */
    while (selector.count)
    {
        /*
         * Step 4: Let the EpollSelector instance wait for an
         * event
         */
        selector.select(TimeSpan.max);

       /* Step 5: Query which event actally happened on which
        * socket.
        */

        auto selection_set = selector.selectedSet;

        if (selection_set) foreach (selection_key; selector)
        {
            /*
             * Step 6: Write to or read from the socket(s).
             */

            Socket socket = cast (Socket) selection_key.conduit;

            // Retrieve the socket connection context.

            SocketItem.Context context =
                cast(SocketItem.Context) selection_key.attachment;

            // Attempt to write all pending data and increase the
            // counter by the number of bytes actually written.

            context.counter +=
                socket.write(context.data[context.counter .. $]);

            /*
             * Step 8: If there is no more data to write for
             * socket, unregister it.
             */
            if (context.counter &gt;= context.data.length)
            {
                selector.unregister(socket);
            }
        }
    }
</pre>
<p>That&#8217;s it! Now we are able to do one write operation on multiple, possibly a huge number of sockets simultaneously without the need of threads. Well, one might object, first the threaded code is much shorter and second with all that code we now can do <em>one</em> write; what about a subsequent read to receive the reply from the server?</p>
<p>Of course, that&#8217;s right. But consider the following: The <code>epoll</code> mechanism can easily handle hundreds of sockets without a significant resource usage overhead. When using threads, for each thread 1 MB of memory is allocated by default on Linux so you easily end up with a hundred MB of memory usage plus the memory that your code allocates. In addition, even if threads are easier to set up, they must be synchronized when using shared resources.</p>
<p>To make each socket read the response data from the server right after sending the request using the <code>EpollSelector</code>, as it is done in the thread-based example, the socket context class must be extended and a socket that finished writing must be re-registered for <code>Event.Read</code>. How this can be done will be the subject of the next post.</p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/09/implementing-an-asynchronous-epoll-based-network-client-with-tango-on-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: removeNode vs. removeChild</title>
		<link>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/</link>
		<comments>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/#comments</comments>
		<pubDate>Tue, 14 Sep 2010 09:33:30 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[cross-browser]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[removeChild]]></category>
		<category><![CDATA[removeNode]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2173</guid>
		<description><![CDATA[Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today's programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework?
Recently there have been a few occasions in which I needed to remove element nodes from the <acronym title="Document Object Model">DOM</acronym>. Learning how to remove element nodes from the <acronym title="Document Object Model">DOM</acronym> can be very useful for a variety of reasons.]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 5: Intonjutsu (escaping and concealment)</strong></p>
<p>Recently there have been a few occasions in which I needed to remove element nodes from the <abbr title="Document Object Model">DOM</abbr>. In some cases the <abbr title="HyperText Markup Language">HTML</abbr> layout needed to be restructured and in other cases I&#8217;ve been asked to make sure that various script tags were removed after their contents had been executed. Learning how to remove element nodes from the <abbr title="Document Object Model">DOM</abbr> can be very useful for a variety of reasons.</p>
<p>The most straightforward way to remove an <abbr title="HyperText Markup Language">HTML</abbr> element is by using its <code>id</code> attribute to select it and then applying the <code>removeNode()</code> method to remove it from the <abbr title="Document Object Model">DOM</abbr>:</p>
<pre class="brush: jscript; title: ; notranslate">
document.getElementById( 'the_element_id' ).removeNode( true );
</pre>
<p>Apparently you must pass the <code>true</code> parameter to the <code>removeNode()</code> method in order for it to work properly. In theory, this will work, but be aware that if the element you are trying to select does not exist then the <abbr title="Javascript">JS</abbr> will throw an error and cease execution immediately. This means that any following <abbr title="Javascript">JS</abbr> code will not be processed. In order to avoid this you&#8217;ll want to check if the element actually exists before attempting to remove it:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_element = document.getElementById( 'the_element_id' );

if ( the_element !== null )
{
    the_element.removeNode( true );
}
</pre>
<p>There is one major problem with this approach; it&#8217;s not cross-browser compatible at all. In my tests the <code>removeNode()</code> method only worked in <abbr title="Internet Explorer">IE</abbr> and Opera, failing in <abbr title="Firefox">FF</abbr>, Google Chrome, and Safari. Due to this unfortunate lack of support we&#8217;re forced to rely on the <code>removeChild()</code> method:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_element = document.getElementById( 'the_element_id' );

if ( the_element !== null )
{
    the_element.parentNode.removeChild( the_element );
}
</pre>
<p>The above <abbr title="Javascript">JS</abbr> code begins by attempting to select the element by the given <code>id</code> value, storing the results to <code>the_element</code> variable. The code then checks this variable to see if the element actually exists or not. This is important to do because if you try to remove an element that does not exist your code will fail and any following <abbr title="Javascript">JS</abbr> will not be executed (as I&#8217;ve already explained above). If the element does exist then we must first select it&#8217;s parent node by using the <code>parentNode()</code> method, after which we can then remove the element itself by applying the <code>removeChild()</code> method and passing it <code>the_element</code> as a parameter. I know this may seem a bit convoluted, but this is the simplest &#8211; and most straightforward &#8211; way to remove an <abbr title="HyperText Markup Language">HTML</abbr> element using purely native and fully cross-browser compatible <abbr title="Javascript">JS</abbr>.</p>
<p>I mentioned in the beginning of this tutorial that I&#8217;m sometimes asked to make sure all included <abbr title="Javascript">JS</abbr> code is removed from the <abbr title="HyperText Markup Language">HTML</abbr> <abbr title="Document Object Model">DOM</abbr> as soon as it&#8217;s finished being executed. I accomplish this by storing the <code>id</code> attribute values of the <code>script</code> elements into a <abbr title="Javascript">JS</abbr> array and then passing this array to a <code>for</code> loop which removes them one by one:</p>
<pre class="brush: jscript; title: ; notranslate">
var script_ids = [ 'first_script_id', 'second_script_id', 'third_script_id' ];

script_ids.reverse();

for ( var index in script_ids )
{
    var the_script = document.getElementById( script_ids[index] );

    if ( the_script !== null )
    {
        the_script.parentNode.removeChild( the_script );
    }
}
</pre>
<p>You&#8217;ll notice that I use the <code>reverse()</code> method on the <code>script_ids</code> array so that it starts from the last script. I do this because I want to remove them in the reverse order they were added. To further explain, I normally store the removal code in a globally accessible <code>function</code> which is defined in the first script I include. For this reason, the first script needs to be the last one I remove or the removal <code>function</code> well no longer be accessible (and thus the scripts won&#8217;t all be removed properly). Here&#8217;s a fuller, working example of this process:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body onload=&quot;remove_all_scripts();&quot;&gt;

    &lt;script type=&quot;text/javascript&quot; id=&quot;first_script_id&quot;&gt;
        var script_ids = [ 'first_script_id' ];

        function remove_script ( script_id )
        {
            var the_script = document.getElementById( script_id );

            if ( the_script !== null )
            {
                the_script.parentNode.removeChild( the_script );
            }
        }

        function remove_all_scripts ()
        {
            script_ids.reverse();

            for ( var index in script_ids )
            {
                remove_script( script_ids[index] );
            }
        }
    &lt;/script&gt;

    &lt;script type=&quot;text/javascript&quot; id=&quot;second_script_id&quot;&gt;
        script_ids.push( 'second_script_id' );
    &lt;/script&gt;

    &lt;script type=&quot;text/javascript&quot; id=&quot;third_script_id&quot;&gt;
        script_ids.push( 'third_script_id' );
    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>It should be pretty clear what I&#8217;m doing in the above example. It&#8217;s important to note that you should wait until the <abbr title="Document Object Model">DOM</abbr> is fully loaded before you actually call the <code>remove_all_scripts()</code> method or you may run into serious trouble attempting to remove a node that only half exists! This is the reason why I&#8217;m relying on the <code>onload</code> attribute of the <code>body</code> element. You might also pay close attention to the fact that I&#8217;m using the <code>push()</code> method to add each script&#8217;s <code>id</code> to the <code>script_ids</code> array. I&#8217;m making sure this happens only once the respective script has actually been added to the page (if you imagine that some of these scripts might be dynamically added then this should begin to make a lot more sense). Alternatively you could specify the list of script <code>id</code>s that you presume to load, but to me it seems much cleaner and more elegant to do it like this.</p>
<p>I hope this tutorial has been helpful in providing you with a way to use native <abbr title="Javascript">JS</abbr> to remove <abbr title="HyperText Markup Language">HTML</abbr> elements from the <abbr title="Document Object Model">DOM</abbr>. Stay tuned for next week&#8217;s discipline: DOMinating iframes.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a><br />
Discipline 3: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Include External JS</a><br />
Discipline 4: <a title="Native Javascript Ninjutsu: Cookie and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">Cookies and Variables</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: Cookies and Variables</title>
		<link>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/</link>
		<comments>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/#comments</comments>
		<pubDate>Mon, 06 Sep 2010 16:43:40 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[cookies]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[variables]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2080</guid>
		<description><![CDATA[Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today's programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework?
Setting cookies with <acronym title="Javascript">JS</acronym> is a technique that I must frequently use in my front-end development missions. Though cookies are not the only way to store and retrieve user data, and often I'm sent out on a <acronym title="Javascript">JS</acronym> mission which involves extracting data from the page itself.]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 4: Chōhō (espionage)</strong></p>
<p>Setting cookies with <abbr title="Javascript">JS</abbr> is a technique that I must frequently use in my front-end development missions. The quickest way to set a cookie is by giving it a <code>name</code> and a <code>value</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'test_cookie=test_value';
</pre>
<p>The code above is pretty self-explanatory, we set the <code>document.cookie</code> object to equal a <code>name</code> and a <code>value</code>. This is the minimum amount of information one needs to define when setting a cookie, though a cookie actually contains all the following details:</p>
<ol>
<li>Name</li>
<li>Content/Value</li>
<li>Domain/Host</li>
<li>Expires</li>
<li>Path</li>
<li>Secure</li>
</ol>
<p>When adding multiple parameters to the cookie we need to separate them with semicolons:</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'test_cookie=test_value; expires=Mon, 06 Sep 2010 11:38:29 GMT; path=/';
</pre>
<p>By default the cookie is set to expire at the end of the session, but in my work I typically want cookies to expire within one hour. I achieve this time restraint by doing the following:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_date = new Date();
var unix_time = the_date.getTime();
var expiration = unix_time + ( 3600 * 1000 );

the_date.setTime( expiration );

document.cookie = 'test_cookie=test_value; expires=' + the_date.toGMTString();
</pre>
<p>First I get the current date and time using the <code>Date()</code> object and set it to <code>the_date</code> variable. I then retrieve the Unix time version of the current date and time by using the <code>getTime()</code> method and save this to the <code>unix_time</code> variable. This stores the time in milliseconds so I can simply add one hour by doing some quick math (60 seconds * 60 minutes * 1000 to get milliseconds + the current Unix time = one hour from now). I then reset <code>the_date</code> variable&#8217;s time to that of the desired expiration. When we finally write the cookie itself we must make sure to use the <abbr title="Greenwich Mean Time">GMT</abbr> string to set the expiration in the proper format.</p>
<p>The <code>domain</code> parameter sets the domain or host on which the cookie is valid. If this isn&#8217;t explicitly set it&#8217;s default value will be the full domain of the page that executes the cookie-setting <abbr title="Javascript">JS</abbr>. If you would like to allow the cookie to be accessed on multiple subdomains then you must set the base domain using two periods:</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'test_cookie=test_value; domain=.testdomain.com';
</pre>
<p>It&#8217;s important to remember that for security reasons you cannot set a cookie to have a cross-domain value. For example, if your cookie is set using <abbr title="Javascript">JS</abbr> on <code>www.testdomain.com</code> then you cannot set the <code>domain</code> parameter to <code>www.othertestdomain.com</code>.</p>
<p>The <code>path</code> parameter is quite similar, as it&#8217;s also used to restrict where (on the server) the cookie is made available. By default the <code>path</code> is set to the root of the current domain (<code>/</code>), but it&#8217;s wise to explicitly set this yourself as some older browsers have been known to have problems if it isn&#8217;t set (such as Netscape).</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'test_cookie=test_value; path=/';
</pre>
<p>If you want to limit the cookie usage to a particular directory on your server you can explicitly set the <code>path</code> parameter:</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'test_cookie=test_value; path=/test_directory';
</pre>
<p>Lastly, the <code>secure</code> parameter allows you to specify whether or not the cookie needs to be accessed over secure (encrypted) connections:</p>
<pre class="brush: jscript; title: ; notranslate">
document.cookie = 'test_cookie=test_value; secure=true';
</pre>
<p>Now let&#8217;s put it all together and set a cookie that has a <code>name</code> and a <code>value</code>, is accessible on all subdomains and directories of the current host but only over secure connections, and expires within one hour:</p>
<pre class="brush: jscript; title: ; notranslate">
var the_date = new Date();
var unix_time = the_date.getTime();
var expiration = unix_time + ( 3600 * 1000 );

the_date.setTime( expiration );

document.cookie = 'test_cookie=test_value; domain=.testdomain.com; path=/; secure=true; expires=' + the_date.toGMTString();
</pre>
<p>That about covers how to set cookies, but obviously setting a cookie doesn&#8217;t help much if we don&#8217;t know how to read it&#8217;s value. Retrieving cookie data is a bit more complex when using purely native <abbr title="Javascript">JS</abbr>. You can use the <code>document.cookie</code> to return all the cookie values:</p>
<pre class="brush: jscript; title: ; notranslate">
var cookies = document.cookie;
document.write( cookies );
</pre>
<p>Do that and you&#8217;ll notice that what you get is a string of cookie names and values separated by semicolons:</p>
<pre class="brush: jscript; title: ; notranslate">
test_cookie=test_value;another_test_cookie=another_test_value;
</pre>
<p>This isn&#8217;t too helpful until we&#8217;ve parsed the information we want out of the string. What I typically do is use the <code>match()</code> method with a regular expression to store the cookie value into an array:</p>
<pre class="brush: jscript; title: ; notranslate">
var cookie_array = document.cookie.match( '(^|;) ?cookie_name=([^;]*)(;|$)' );

if ( cookie_array )
{
    var cookie_value = cookie_array[2]
}
</pre>
<p>I won&#8217;t explain the regular expression I&#8217;ve used in great detail &#8211; as the topic of regular expressions could easily make up a whole series of blog articles by itself &#8212; but I will summarize by saying that it finds the value and stores it into the second element of an array. Once we set this array we must check if it actually exists before attempting to extract the cookie value. Note that this regular expression will only return the value of the first cookie whose name matches the <code>cookie_name</code> string, therefore if you have two cookies set with the same name you will not be able to retrieve both values using this method. This is a rare case and for that reason I&#8217;m not worried about the use of this technique.</p>
<p>To update a cookie you can simply rewrite it using the methods I&#8217;ve shown above, although it&#8217;s important to note that if you change the <code>domain</code> parameter of a cookie you will actually end up with two cookies. This is because the original is not automatically removed. The best way to remove cookies is to set their <code>expires</code> parameter to a past date, and all their other parameters to <code>null</code> (or an empty string). Even once you&#8217;ve done this the cookie may still appear to be available. Most web browsers need a restart to refresh (and delete) their cookie data completely.</p>
<p>Cookies are not the only way to store and retrieve user data, and often I&#8217;m sent out on a <abbr title="Javascript">JS</abbr> mission which involves extracting data from the page itself. It&#8217;s very common that third party scripts will save their variables outside of the global namespace and this makes these variables impossible to access directly. For example take the following <abbr title="HyperText Markup Language">HTML</abbr> page:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;

   &lt;script type=&quot;text/javascript&quot;&gt;
        function set_variable()
        {
            var the_variable = 'the value';
        }

        set_variable();
    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Lets pretend that the above <abbr title="HyperText Markup Language">HTML</abbr> page belongs to our client. Imagine that the <code>script</code> tag and its contents were added to the client&#8217;s webpage by a third party developer and that we&#8217;re not able to doctor or edit them whatsoever. Further imagine that all we&#8217;re allowed to do is include our own <code>script</code> after theirs. Because <code>the_variable</code> is defined within the scope of the <code>set_variable()</code> function we&#8217;re completely unable to access its value directly. We can however use some <abbr title="Document Object Model">DOM</abbr> parsing tricks to retrieve the value:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type=&quot;text/javascript&quot;&gt;
        function set_variable()
        {
            var the_variable = 'the value';
        }

        set_variable();
    &lt;/script&gt;

    &lt;script&gt;
        var scripts = document.getElementsByTagName( 'script' );

        for ( var index in scripts )
        {
            if ( scripts[index].nodeType === 1 )
            {
                var script_code = scripts[index].innerHTML;
                parsed_code = script_code.match( &quot;the_variable = '(.*?)'&quot; );

                if ( parsed_code !== null )
                {
                    the_value = parsed_code[1];
                }
            }
        }
    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>First we store all the <code>script</code> tags from the <abbr title="Document Object Model">DOM</abbr> into an object called <code>scripts</code>. Then we run a <code>for</code> loop on this object, checking if each node is an element (<code>nodeType === 1</code>). If the node is an element then we proceed by storing its <code>innerHTML</code> to a string called <code>script_code</code> and then use the <code>match()</code> method to run a fairly straight forward regular expression on the string. If the results aren&#8217;t <code>null</code> then we store the found value to our final variable. Be aware that it may be necessary to slightly modify the regular expression pattern used to match different situations (such as different variable names, single quotes versus double quotes around the value, spaces before and after the equals sign, et cetera).</p>
<p>I hope this article has been helpful in providing you with a way to use native <abbr title="Javascript">JS</abbr> to deal with cookies and non-global variables in your scripts. Stay tuned for next week&#8217;s discipline: <a title="Native Javascript Ninjutsu: removeNode vs. removeChild" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-removenode-vs-removechild/">removeNode vs. removeChild</a>.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a><br />
Discipline 3: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Include External JS</a></p>
<p><strong>Resources</strong><br />
<a title="The Unofficial Cookie FAQ" href="http://www.cookiecentral.com/faq/">The Unofficial Cookie FAQ</a><br />
<a title="W3Schools' Javascript Cookies Tutorial" href="http://www.w3schools.com/JS/js_cookies.asp">W3Schools&#8217; Javascript Cookies Tutorial</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: Include External JS</title>
		<link>http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/</link>
		<comments>http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 08:30:29 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[HTTP]]></category>
		<category><![CDATA[HTTPS]]></category>
		<category><![CDATA[iframe]]></category>
		<category><![CDATA[img]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=2009</guid>
		<description><![CDATA[Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today's programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework?
Using native <acronym title="Javascript">JS</acronym> to include external scripts is pretty fun and easy to do.]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 3: Shinobi-iri (stealth and entering methods)</strong></p>
<p>Using native <abbr title="Javascript">JS</abbr> to include external scripts is pretty fun and easy to do. Here&#8217;s a simple example below:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script id=&quot;first-script&quot; type=&quot;text/javascript&quot;&gt;
        (
            function ()
            {
                var s = document.createElement( 'script' );
                s.id = 'second-script';
                s.type = 'text/javascript';
                s.async;
                s.src = ( 'https:' == document.location.protocol ? 'https://' : 'http://' ) + 'domain.com/second-script.js';
                var x = document.getElementById( 'first-script' );
                x.parentNode.insertBefore( s, x );
            }
        )();
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>As you can see, the <abbr title="HyperText Markup Language">HTML</abbr> file has a <code>script</code> tag in it that contains an anonymous function. The anonymous function is wrapped in parentheses and followed by <code>();</code> so that it will execute itself immediately. The reason we do this is so that the variables used are explicitly scoped within this function only. This prevents possible overlap from any other <abbr title="Javascript">JS</abbr> variables that may exist in the <abbr title="HyperText Markup Language">HTML</abbr>. While this may seem to be a bit paranoid for smaller projects, I&#8217;m often asked to complete <abbr title="Javascript">JS</abbr> missions which involve including external scripts into third party, client-owned pages, and thus I have no control over &#8211; and sometimes no idea about &#8211; what may already exist in the page.</p>
<p>The anonymous function starts by creating a script element and saving it to a variable (<code>s</code>, in this case). The element is given a handful of attributes: an <code>id</code>, a <code>type</code>, an <code>async</code> value, and a <code>src</code>. These should all be pretty straightforward and self-explanatory, though the <code>aync</code> attribute is a bit interesting. The attribute sets the script to load asynchronously, and it works the same as the <code>disabled</code> and <code>checked</code> attributes, in that it&#8217;s value doesn&#8217;t matter, but only it&#8217;s presence holds meaning. If the <code>async</code> attribute exists it will automatically be considered to hold the value of <code>true</code>. Considering this, you don&#8217;t need to actually set the <code>async</code> attribute to any value, but instead you can simple define the attribute and it will work as expected. Keep in mind that the <code>async</code> attribute is a new <abbr title="HyperText Markup Language">HTML</abbr>5 attribute and so it isn&#8217;t supported in all browsers yet.</p>
<p>After we set all the proper attributes for the element we then find the current script and insert our new script directly before it. Alternatively, if we&#8217;d like to insert our new script directly after the current script we can do the following:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script id=&quot;first-script&quot; type=&quot;text/javascript&quot;&gt;
        (
            function ()
            {
                var s = document.createElement( 'script' );
                s.id = 'second-script';
                s.type = 'text/javascript';
                s.async;
                s.src = ( 'https:' == document.location.protocol ? 'https://' : 'http://' ) + 'domain.com/second-script.js';
                var x = document.getElementById( 'first-script' );
                x.parentNode.insertBefore( s, x.nextSibling );
            }
        )();
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If for some reason you can&#8217;t &#8211; or don&#8217;t want to &#8211; give the first script an <code>id</code> attribute then you can include the second script like so:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        (
            function ()
            {
                var s = document.createElement( 'script' );
                s.type = 'text/javascript';
                s.async;
                s.src = ( 'https:' == document.location.protocol ? 'https://' : 'http://' ) + 'domain.com/script.js';
                var x = document.getElementByTagName( 'script' )[0];
                x.parentNode.insertBefore( s, x );
            }
        )();
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This will return an array of all the <code>script</code> tags in the <abbr title="Document Object Model">DOM</abbr>. It will then save the first element in this array to the variable <code>x</code>. Sometimes this will be the current <code>script</code> tag, but other times (depending entirely on the <abbr title="HyperText Markup Language">HTML</abbr> structure of the page) this could be earlier <code>script</code> tags. The point of this method is to make sure the new <abbr title="Javascript">JS</abbr> is included to the page in an area that makes the most sense for the page owner. This can be very important when working with third party, client-owned websites.</p>
<p>Cross-browser compatibility is a big deal and even though it seems like everyone is browsing with <abbr title="Javascript">JS</abbr> enabled these days, I believe it&#8217;s still important that we make things work for those who aren&#8217;t. In most circumstances where I&#8217;m forced to use native <abbr title="Javascript">JS</abbr> to include scripts in websites it&#8217;s very likely that these scripts will be used to trigger server-side code. The end client may not always allow me to include server side code directly in their website itself, so a helpful workaround is to load the server side code into an <code>img</code> tag and wrap this in a <code>noscript</code> tag:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        (
            function ()
            {
                var s = document.createElement( 'script' );
                s.type = 'text/javascript';
                s.async;
                s.src = ( 'https:' == document.location.protocol ? 'https://' : 'http://' ) + 'domain.com/script.js';
                var x = document.getElementByTagName( 'script' )[0];
                x.parentNode.insertBefore( s, x );
            }
        )();
    &lt;/script&gt;
    &lt;noscript&gt;
        &lt;img src=&quot;http://domain.com/server-side-script.php&quot; width=&quot;1&quot; height=&quot;1&quot; /&gt;
    &lt;/noscript&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>What this will do is execute the server side code instead of actually loading an image. Although this doesn&#8217;t allow you to execute <abbr title="Javascript">JS</abbr>, it does help to provide a work around and an alternative means of firing third party code when you need your solution to be as cross-browser compatible as possible.</p>
<p>There&#8217;s a third way to include <abbr title="Javascript">JS</abbr> that I would like to share with you and it involves the use of the <abbr title="HyperText Markup Language">HTML</abbr> <code>iframe</code> tag. The initial <abbr title="Javascript">JS</abbr> would look like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        (
            function ()
            {
                var s = document.createElement( 'iframe' );
                s.src = ( 'https:' == document.location.protocol ? 'https://' : 'http://' ) + 'domain.com/iframe-script.html';
                var x = document.getElementByTagName( 'script' )[0];
                x.parentNode.insertBefore( s, x );
            }
        )();
    &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The code in <code>iframe-script.html</code> would look like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;script type=&quot;text/javascipt&quot;&gt;
        // insert your javascript code here!
    &lt;/script&gt;
&lt;/body&gt;
</pre>
<p>There are times when it may make more sense to use an <code>iframe</code>, though I do not often find them that useful, and the above code has some problematic points. For starters, if the initial webpage you are working with has its scripts all in the <code>head</code> tag then you will be attempting to insert the <code>iframe</code> there, which is not a good idea. Furthermore, it is very difficult to pass <abbr title="Javascript">JS</abbr> variables and make calls to functions between the parent page and the child <code>iframe</code> within it. In fact, if these pages are either from different domains or even use different protocols (<abbr title="Hypertext Transfer Protcol"><code>HTTP</code></abbr> versus <abbr title="Hypertext Transfer Protcol Secure"><code>HTTPS</code></abbr>) then it will be impossible to communicate between them using <abbr title="Javascript">JS</abbr>. To add to the problems the <code>iframe</code> tag is also not supported in all browsers. For these reasons I avoid the use of <code>iframe</code> tags whenever possible.</p>
<p>I hope this article has been helpful in providing you with a way to use native <abbr title="Javascript">JS</abbr> to include external scripts into your pages. Stay tuned for next week&#8217;s discipline: <a title="Native Javascript Ninjutsu: Cookies and Variables" href="http://blog.sociomantic.com/2010/09/native-javascript-ninjutsu-cookies-and-variables/">Cookies and Variables</a>.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a><br />
Discipline 2: <a title="Native Javascript Ninjutsu: Dynamic JS with PHP" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/">Dynamic JS with PHP</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Native Javascript Ninjutsu: Dynamic JS with PHP</title>
		<link>http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/</link>
		<comments>http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/#comments</comments>
		<pubDate>Mon, 23 Aug 2010 17:10:39 +0000</pubDate>
		<dc:creator>Dylan</dc:creator>
				<category><![CDATA[Code Talk]]></category>
		<category><![CDATA[dynamic scripts]]></category>
		<category><![CDATA[front-end programming]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JS]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[variables]]></category>
		<category><![CDATA[web development]]></category>
		<category><![CDATA[webdev]]></category>

		<guid isPermaLink="false">http://www.sociomantic.com/?p=1924</guid>
		<description><![CDATA[Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today's programmers can write pure native Javascript without the aid of a framework? How many can perform AJAX requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework?
Dynamic scripting allows your <acronym title="Javascript">JS</acronym> to be changed based on the server side or client side situation (or both); different scenarios call for different measures, different variables, and sometimes even completely different code altogether.]]></description>
			<content:encoded><![CDATA[<p><img class="alignright  wp-image-1915" title="200px-Ninja_kanji.svg" src="http://blog.sociomantic.com/wp-content/uploads/200px-Ninja_kanji.svg_-155x300.png" alt="Ninja kanji" /></p>
<p><strong>Sensei Says (dark ages, to dojos, to disciplines)</strong></p>
<p>Javascript used to be a dark and ancient art, looked down upon by many web developers as a dishonorable &#8211; even malicious &#8211; &#8216;copy and paste&#8217; language. Macromedia&#8217;s Shockwave &#8211; which later became Macromedia Flash, which even later became Adobe Flash &#8211; pushed audio, video, and interactive motion graphics onto the web in a cross-browser compatible format that all but decimated the need and appeal for Javascript. What little Javascript community there was began to seriously dwindle and die out.</p>
<p>And then the frameworks came to rise: <a title="Dojo" href="http://dojotoolkit.org/" target="_blank">Dojo</a>, <a title="Yahoo! UI Library" href="http://developer.yahoo.com/yui/" target="_blank">Yahoo! UI Library</a>, <a title="Google Web Toolkit" href="http://code.google.com/webtoolkit/" target="_blank">Google Web Toolkit</a>, <a title="jQuery" href="http://jquery.com/" target="_blank">jQuery</a>, <a title="Prototype" href="http://www.prototypejs.org/" target="_blank">Prototype</a>, <a title="MooTools" href="http://mootools.net/" target="_blank">MooTools</a>, and <a title="List of AJAX frameworks" href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript" target="_blank">many more</a>. With these powerful armies by its side, the Javascript community quickly grew and regained its honor, competing heavily with the fluid animation and complex, real-time interactivity that Flash had delivered for years.</p>
<p>Javascript now seems to be a strong, healthy, and widely accepted language, frequently used and relied upon by web developers across the land. Yet how many of today&#8217;s programmers can write pure native Javascript without the aid of a framework? How many can perform <abbr title="Asynchronous JavaScript and XML">AJAX</abbr> requests without a framework? And most importantly, how many can craft fully cross-browser compatible code without a framework? In order to not become dependent on the frameworks &#8211; and thus risk sliding backwards into the dark ages &#8211; we must maintain a wide variety of practices: these are the native Javascript disciplines.</p>
<p><strong>Discipline 2: Hensōjutsu (disguise and impersonation)</strong></p>
<p>I mostly use static scripts when working with <abbr title="Javascript">JS</abbr>, though recently I&#8217;ve completed quite a few missions that involved the use of dynamic scripts. Dynamic scripting allows your <abbr title="Javascript">JS</abbr> to be changed based on the server side or client side situation (or both); different scenarios call for different measures, different variables, and sometimes even completely different code altogether.</p>
<p>Let&#8217;s begin with variables. Passing variables from <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> to internal <abbr title="Javascript">JS</abbr> is very simple:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var numeric_variable = &lt;?php echo $numeric_value ?&gt;;
        var string_variable = '&lt;?php echo $string_value ?&gt;';
    &lt;/script&gt;
&lt;/head
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>I&#8217;ve shown two examples above, the latter of which passes a string value to <abbr title="Javascript">JS</abbr>. It&#8217;s important to note that you must include quotes around the <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> block. This insures that the outputted value is properly wrapped in quotes, otherwise it could very well break your <abbr title="Javascript">JS</abbr>.</p>
<p>It&#8217;s also important to note that the above code relies on <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> to create and pass the values to the <abbr title="Javascript">JS</abbr> variables, and therefore the file itself must be parsed as a <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> file by the server. This is most easily done by making sure the file has a <code>.php</code> extension (suffix). There will certainly be some cases in which you don&#8217;t have the option of changing the main webpage you are working with to a <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> file. In that case there is an alternative solution, but it only works with external <abbr title="Javascript">JS</abbr>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;some_script.php&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The above <abbr title="HyperText Markup Language">HTML</abbr> code includes an external <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> script that contains the following code:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
echo &quot;var string_variable = '$string_value';&quot;;
?&gt;
</pre>
<p>This echoes the dynamic <abbr title="Javascript">JS</abbr> that should be included into the <abbr title="HyperText Markup Language">HTML</abbr> page. The <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> values are passed directly in the echo string. This works because we&#8217;re using double quotes around the echo string and I think it&#8217;s one of the most convenient ways to store <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> values in <abbr title="Javascript">JS</abbr> variables. If you need to use double quotes within the <abbr title="Javascript">JS</abbr> code itself then you must either escape those quotes with a back slash or echo a list of strings/values allowing you to switch to single quotes:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
echo
&quot;var string_variable = '\&quot;$string_value\&quot;';&quot;;
?&gt;
</pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
echo
&quot;var string_variable = '&quot;, '&quot;', $string_value, '&quot;', &quot;';&quot;;
?&gt;
</pre>
<p>The latter approach can be quite hard to read, and for this reason I typically stick with escaping double quotes whenever I&#8217;m required to use them. When you need to echo multiple lines of <abbr title="Javascript">JS</abbr> you can do so by simply putting lines break in the echo string:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
echo
&quot;var numeric_variable = $numeric_value;
var string_variable = '$string_value';&quot;;
?&gt;
</pre>
<p>Although this has a purely aesthetic effect on the code, I find it to be invaluable in keeping my <abbr title="Javascript">JS</abbr> readable, especially considering that the code itself is stored inside of a <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> string (and thus I lose the benefit of syntax highlighting that would normally be applied within my code editor).</p>
<p>Very often my front end missions involve passing values from the client side to the server side. When including an external script you can add query parameters to the source URL and have these values passed by <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> to the echoed <abbr title="Javascript">JS</abbr>:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
    &lt;script type=&quot;text/javascript&quot; src=&quot;some_script.php?string_value=Hello World!&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;/html&gt;
</pre>
<p>The above <abbr title="HyperText Markup Language">HTML</abbr> code includes an external <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> script that contains the following code:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
$string_value = $_GET['string_value'];
echo &quot;var string_variable = '$string_value';&quot;;
?&gt;
</pre>
<p>The <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> code retrieves the value from the header <code>GET</code> method array and echoes it with the <abbr title="Javascript">JS</abbr> back to the <abbr title="HyperText Markup Language">HTML</abbr> page.</p>
<p>Earlier this summer I finished <a title="Loyalty" href="http://apps.facebook.com/loyalemusic/" target="_blank">my first Facebook Application</a>, in which my work required me to pass an entire <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> array to be stored as a <abbr title="Javascript">JS</abbr> array. The technique I used may be helpful in illustrating that you can achieve quite a lot with a bit of creativity and understanding of both languages:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
    &lt;script type=&quot;text/javascript&quot;&gt;
        var new_array = new Array();
&lt;?php
    foreach( $some_array as $array_key =&gt; $array_value )
    {
?&gt;
        new_array[&lt;?php echo $array_key; ?&gt;] = '&lt;?php echo $array_value; ?&gt;';
&lt;?php
    }
?&gt;
    &lt;/script&gt;
&lt;/head&gt;
&lt;/html&gt;
</pre>
<p>The above code prepares a new array in <abbr title="Javascript">JS</abbr> and then runs a <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> <code>foreach</code> loop. Each time the loop is executed the line of <abbr title="Javascript">JS</abbr> inside of it is added to the page, complete with the properly echoed <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> values. Once the server side processing is complete, the client side will execute all the prepared lines of <abbr title="Javascript">JS</abbr> and you should have an array that is identical to your <abbr title="PHP: Hypertext Preprocessor">PHP</abbr> original; the same keys, and their same values.</p>
<p>By now you should be able to imagine the variety of ways that dynamic <abbr title="Javascript">JS</abbr> can be useful. You can use these same techniques to add more dynamic functionality to your front end projects. Now go out there, practice your native, dynamic <abbr title="Javascript">JS</abbr> in the field, and stay tuned for next week&#8217;s discipline: <a title="Native Javascript Ninjutsu: Include External JS" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-include-external-js/">Including External JS</a>.</p>
<p><strong>Previous Disciplines</strong><br />
Discipline 1: <a title="Native Javascript Ninjutsu: AJAX with XHR" href="http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-ajax-with-xhr/">AJAX with XHR</a></p>
<p><strong>Are you smart? Innovative? Driven? If you&#8217;re interested in working on challenging projects in one of the world&#8217;s most fast-paced industries, why not check out the openings on our <a href="http://www.sociomantic.com/careers/" target="_blank">Careers</a> page?</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.sociomantic.com/2010/08/native-javascript-ninjutsu-dynamic-js-with-php/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

