<?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>Way of Spark &#187; Javascript</title>
	<atom:link href="http://wayofspark.com/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://wayofspark.com</link>
	<description>problèmes et solutions de l&#039;informatique de tous les jours, pour nous, les devs.</description>
	<lastBuildDate>Sat, 14 Aug 2010 11:31:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>SmartTextBox</title>
		<link>http://wayofspark.com/projects/smarttextbox/</link>
		<comments>http://wayofspark.com/projects/smarttextbox/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 08:21:18 +0000</pubDate>
		<dc:creator>Spark</dc:creator>
				<category><![CDATA[dev]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[smarttextbox]]></category>

		<guid isPermaLink="false">http://wayofspark.com/</guid>
		<description><![CDATA[2010-08-12 &#8211; Important  : Currently, the jQuery plugin site is broken and developpers cannot add new releases to their projects. While this lasts, please be sure to download the lastest version from the googlecode download page, and not from the jQuery plugin site. Introduction SmartTextBox is a jQuery plugin that turns text inputs into javascript [...]]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ff0000;">2010-08-12 &#8211; Important   : Currently, the jQuery plugin site is broken and developpers cannot  add new releases to their projects. While this lasts, please be sure to  download the lastest version from the googlecode download page, and not  from the jQuery plugin site.</span></p>
<h3>Introduction</h3>
<p>SmartTextBox is a jQuery plugin that turns text inputs into javascript driven widget that allow navigating the options using keyboard, auto completion and many other features, while being fully customizable. The plugin is inspired by  Guillermo Rauch&#8217;s TextBoxList, at the time his plugin was only available on mootools. The plugin was originally supposed to be used only on internal projects, but as time passed, I decided to clean it up and to publish it in jQuery plugin&#8217;s list.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-413" title="SmartTextBox" src="http://wayofspark.com/wp-content/uploads/2010/08/SMT_RC2.png" alt="" width="518" height="115" /></p>
<h3>Current version</h3>
<p>The current version of SmartTextBox is <strong>1.2.0-rc1</strong></p>
<h3>Demo</h3>
<p>A demo page of the most common usages of the SmartTextBox plugin <a href="http://wayofspark.com/static/projects/smarttextbox/demo.html">is available here.</a></p>
<h3>Sources</h3>
<p>The sources are availables in the WOPU project, hosted by googlecode, <a href="http://code.google.com/p/wopu/">there</a></p>
<h3>Download</h3>
<p>The plugin is downloadable <a href="http://code.google.com/p/wopu/downloads/list">here</a>. For direct download of the lastest version just click <a href="http://wopu.googlecode.com/files/SmartTextBox-1.2.0-rc1.zip">there</a>.</p>
<h3>Requirements</h3>
<p>SmartTextBox required jQuery 1.2 or higher.</p>
<h3>Installation</h3>
<p>Just download the plugin, be sure you already have jQuery included on your pages, copy the files, then simply add in the headers :</p>
<pre>&lt;link charset="utf-8" media="screen" type="text/css" href="/path/to/smarttextbox/SmartTextBox.css" rel="stylesheet"/&gt;
&lt;script charset="utf-8" type="text/javascript" src="/path/to/smarttextbox/SmartTextBox.js"&gt;&lt;/script&gt;</pre>
<h3>License</h3>
<p>SmartTextBox comes under the GPL license.</p>
<h3>Browsers support</h3>
<p>SmartTextBox supports all major browser (IE6/7/8, FF2/3, Chrome, Safari, Opera)</p>
<h3>Usage</h3>
<p>SmartTextBox follows the jQuery principles in terms of usage and accessibility. Creating a SmartTextBox from an input is very easy :</p>
<pre class="prettyprint javascript">$("#myInput").smartTextBox();</pre>
<p>SmartTextBox is fully customizable, and options can be passed as follow :</p>
<pre class="prettyprint javascript">$("#myInput").smartTextBox({submitKeys : [13], autocomplete : true, separator : ";"});</pre>
<h3>Options</h3>
<p>Here is the list of options usable when creating a SmartTextBox :</p>
<table class="javadoc">
<thead>
<td>key</td>
<td>default</td>
<td>description</td>
</thead>
<tbody>
<tr>
<td>autocomplete</td>
<td>true</td>
<td>activate or desactivate the autocompletion feature</td>
</tr>
<tr>
<td>minSearchLength</td>
<td>2</td>
<td>min length of text to type to receive autocompletion suggestions</td>
</tr>
<tr>
<td>maxResults</td>
<td>10</td>
<td>max number of results to display by autocompletion widget</td>
</tr>
<tr>
<td>caseSensitive</td>
<td>false</td>
<td>if true, search will be case sensitiv</td>
</tr>
<tr>
<td>highlight</td>
<td>true</td>
<td>highlight matching parts in autocompletion results</td>
</tr>
<tr>
<td>fullSearch</td>
<td>true</td>
<td>search at start of values or in all the string</td>
</tr>
<tr>
<td>placeholder</td>
<td>see desc.</td>
<td>placeholder text to display when autocomplete widget enter focus. Default to &#8220;Please start typing to receive suggestions&#8221;</td>
</tr>
<tr>
<td>autocompleteValues</td>
<td>[]</td>
<td>List of values to be used as suggestions for autocompletion</td>
</tr>
<tr>
<td>autocompleteUrl</td>
<td>null</td>
<td>url to use to load autocomplete values at initialization. The return format must be a simple JSON object with a &#8220;values&#8221; key containing a list of String</td>
</tr>
<tr>
<td>onlyAutocomplete</td>
<td>false</td>
<td>if set to true, boxes can only be created from autocomplete values</td>
</tr>
<tr>
<td>uniqueValues</td>
<td>true</td>
<td>if true, values can only be added once</td>
</tr>
<tr>
<td>hideEmptyInputs</td>
<td>true</td>
<td>To hide or to display empty inputs on a blurr</td>
</tr>
<tr>
<td>editOnFocus</td>
<td>false</td>
<td>When true, box elements will change back to edit mode when focused</td>
</tr>
<tr>
<td>editOnDoubleClick</td>
<td>false</td>
<td>When true, box elements will change back to edit mode when double clicked</td>
</tr>
<tr>
<td>submitKeys</td>
<td>[13]</td>
<td>List of key codes used to save an input to box (default : enter key)</td>
</tr>
<tr>
<td>submitChars</td>
<td>[ ";", ","]</td>
<td>List of chars used to save input to box</td>
</tr>
<tr>
<td>containerClass</td>
<td>&#8220;smartTextBox&#8221;</td>
<td>Base css class used on SmartTextBox containers and elements</td>
</tr>
<tr>
<td>separator</td>
<td>&#8220;;&#8221;</td>
<td>separator character used to split values from original input and serialize it back</td>
</tr>
<tr>
<td>updateOriginal</td>
<td>true</td>
<td>If true, the original input value will be updated everytime the SmartTextBox values changes.</td>
</tr>
<tr>
<td>debug</td>
<td>false</td>
<td>If true, will output some debug logs to the firebug console (and will make IE crash on the missing console.log object)</td>
</tr>
</tbody>
</table>
<h3>Events</h3>
<p>SmartTextBox also allow the wiring of custom user events. All events handlers are fired with 2 parameters : the first is the element triggering the event, the second is the SmartTextBox object which the element is attached to. The events are customizable by the following keys in the options :</p>
<table class="javadoc">
<thead>
<td>key</td>
<td>default</td>
<td>description</td>
</thead>
<tbody>
<tr>
<td>onElementAdd</td>
<td>null</td>
<td>Fired when a box element is added</td>
</tr>
<tr>
<td>onElementRemove</td>
<td>null</td>
<td>Fired when a box element is removed</td>
</tr>
<tr>
<td>onElementFocus</td>
<td>null</td>
<td>Fired when an element is focused</td>
</tr>
<tr>
<td>onElementBlur</td>
<td>null</td>
<td>Fired when an element looses focus</td>
</tr>
</tbody>
</table>
<h3>API</h3>
<p>Once created, the SmartTextBox API calls can be accessed through the $(&#8220;#myInput&#8221;).smartTextBox method :</p>
<table class="javadoc">
<thead>
<td>method</td>
<td>usage</td>
<td>description</td>
</thead>
<tbody>
<tr>
<td>add</td>
<td>
<pre class="prettyprint">$(el).smartTextBox("add","a label")</pre>
</td>
<td>Add a box to the end of the SmartTextBox list</td>
</tr>
<tr>
<td>remove</td>
<td>
<pre class="prettyprint">$(el).smartTextBox("remove",labelOrIndex)</pre>
</td>
<td>Remove a box from the list. Can be used to remove by label or by index</td>
</tr>
<tr>
<td>load</td>
<td>
<pre class="prettyprint">$(el).smartTextBox("load", values)</pre>
</td>
<td>Empty the list, and then add all the specified values. &#8220;values&#8221; can be a list of string, or a string with the options.separator separator char</td>
</tr>
<tr>
<td>clear</td>
<td>
<pre class="prettyprint">$(el).smartTextBox("clear")</pre>
</td>
<td>Empty the current list</td>
</tr>
<tr>
<td>autocomplete</td>
<td>
<pre class="prettyprint">$(el).smartTextBox("autocomplete", values)</pre>
</td>
<td>Sets the list of values to be used as suggestions for autocompletion. The value can be a list of string, or a string with the options.separator separator char</td>
</tr>
</tbody>
</table>
<h3>Changelog</h3>
<h4><strong>1.2.0-rc1 &#8211; 2010-08-14</strong></h4>
<ul>
<li><strong>New features</strong></li>
</ul>
<p>- new &#8216;autocompleteUrl&#8217; option : can now load list of autocomplete values from an json ajax call (one time values load)</p>
<p>- new &#8216;onlyAutocomplete&#8217; option (default to false). When set to true, The SmartTextBox will only accept labels added from the autocompletion list.</p>
<p>- new &#8216;uniqueValues&#8217; option (default to true). When set to true, the SmartTextBox will only accept the labels once (that mean a label cannot be added more than once). Also, when this mode is active, the autocompletion will not propose already-added labels.</p>
<p>- autocompletion search mode can now be choosen between &#8216;start of word&#8217; and &#8216;full text search&#8217; ( see the &#8216;fullSearch&#8217; option )</p>
<ul>
<li><strong>Changes</strong></li>
</ul>
<p>- major change in the autocomplete configuration : autocompleteOptions map has been remove. Now autocomplete configuration is made directly in the SmartTextBox options map.</p>
<p>This cause the following options rename :</p>
<p>- minLength renamed to minSearchLength</p>
<ul>
<li><strong>Bug fixes</strong></li>
</ul>
<p>- deleting elements using keyboard now correctly focus previous or next element.</p>
<p>- autocomplete options are now correctly passed to autocomplete instance at SmartTextBox initialization.</p>
<p>- autocomplete results are now correctly highlighted.</p>
<h4><strong>1.1.2 &#8211; 2010-08-12</strong></h4>
<ul>
<li><strong>Bug fixes</strong></li>
</ul>
<p>- backspace key now works back as intended when typing text in boxes</p>
<h4><strong>1.1.1 &#8211; 2010-08-12</strong></h4>
<ul>
<li><strong>Bug fixes</strong></li>
</ul>
<p>- fix plugin for IE6 ( stupid comma&#8230; )</p>
<p>- use of backspace key to delete boxes now longer cause the browser to go to last page</p>
<h4><strong>1.1 &#8211; 2010-08-03</strong></h4>
<ul>
<li><strong>New features</strong></li>
</ul>
<p><strong>- </strong>added custom event<strong> </strong>wiring capability<strong><br />
</strong></p>
<ul>
<li> <strong>API Changes</strong></li>
</ul>
<p>- the method &#8220;values&#8221; renamed to &#8220;load&#8221;</p>
<ul>
<li><strong>Bug fixes</strong></li>
</ul>
<p>- the API methods &#8220;load&#8221; and &#8220;autocomplete&#8221; can now work with lists as intended</p>
<p>- the API method &#8220;remove&#8221; can now work with an index as intended</p>
<h4><strong>1.0 &#8211; 2010-08-02</strong></h4>
<p>- Initial public release.</p>
    ]]></content:encoded>
			<wfw:commentRss>http://wayofspark.com/projects/smarttextbox/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Javascript et les arguments optionnels</title>
		<link>http://wayofspark.com/2008/07/23/javascript-et-les-arguments-optionnels/</link>
		<comments>http://wayofspark.com/2008/07/23/javascript-et-les-arguments-optionnels/#comments</comments>
		<pubDate>Wed, 23 Jul 2008 15:57:23 +0000</pubDate>
		<dc:creator>Spark</dc:creator>
				<category><![CDATA[Dev]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://wayofspark.com/?p=5</guid>
		<description><![CDATA[Javascript est un langage de script relativement puissant, mais dont certaines fonctionnalités sont souvent peu ou pas connu de la majorité. La gestion des arguments optionnels lors de l&#8217;appel à des fonction en fait parti. Dans ce tutorial, j&#8217;expliquerai comment créer une méthode gérant un argument optionnel, puis une autre pouvant recevoir un nombre variable [...]]]></description>
			<content:encoded><![CDATA[<p>Javascript est un langage de script relativement puissant, mais dont certaines fonctionnalités sont souvent peu ou pas connu de la majorité. La gestion des arguments optionnels lors de l&#8217;appel à des fonction en fait parti.</p>
<p>Dans ce tutorial, j&#8217;expliquerai comment créer une méthode gérant un argument optionnel, puis une autre pouvant recevoir un nombre variable d&#8217;argument.<span id="more-5"></span></p>
<h3>Arguments optionnels</h3>
<p>Mettont que nous ayons besoin de trier une liste. Pour ce faire, nous créons une méthode qui s&#8217;occupe de trier la liste, puis de la retourner ( dans l&#8217;exemple, la fonction fait juste appel à la méthode sort de la liste, mais on imagine la déclaration d&#8217;une vrai méthode de tri puis de son exécution )</p>
<p>On obtientrait donc quelque chose de ce type :</p>
<pre class="prettyprint">mySort = function(l){
    l.sort();
    return l;
};
>>> mySort([4,2,3]);
[2,3,4]</pre>
<p>Cependant, plus tard lors de notre développement, apparait un autre besoin : il faudrait pouvoir trier la liste, mais en sens inverse cette fois-ci.</p>
<p>Plusieurs solutions apparaissent alors :</p>
<p>La premiere serait de séparer les deux étapes, en effectuant d&#8217;abord l&#8217;appel à mySort(), puis ensuite à myReverse() par exemple ( qui, ferait d&#8217;ailleurs simplement return l.reverse() dans cet exemple très basique ). Mais cela allourdirait le code.</p>
<p>La seconde est de rajouter un second paramètre à mySort, pour spécifier l&#8217;ordre dans lequel on veut trier la liste.<br />
On obtiendrait alors quelque chose de ce genre :</p>
<pre class="prettyprint">mySort = function(l, order){
    l.sort();
    if(order=="reverse") l.reverse();
    return l;
};
>>> mySort([2,4,3], "normal")
[2,3,4]
>>> mySort([2,4,3], "reverse")
[4,3,2]</pre>
<p>On observe effectivemment qu&#8217;en fonction du second paramètre ( &#8220;normal&#8221; ou &#8220;reverse&#8221; ), le sens du tri est, ou non, inversé.</p>
<p>Seulement voila, cela oblige à passer un second parametre à chaque appel de sa méthode. Paramètre au final inutile si on veut trier la liste &#8216;simplement&#8217;, sans l&#8217;inverser.</p>
<p>Et bien en fait (oh surprise!) non.</p>
<p>En effet, une astuce trop peu connue des débutants est l&#8217;utilisation de paramètres optionnels. Un paramètre contenu dans la déclaration d&#8217;une méthode et non envoyé lors de l&#8217;appel de cette dernière ne pose,en fait, pas de problème. La variable est simplement considérée comme étant à la valeur null.</p>
<p>exemple :</p>
<pre class="prettyprint">f = function(a){
    return a
}
>>> f(2)
2
>>> f()
null</pre>
<p>On constate qu&#8217;effectivemment, quand le paramètre &#8216;a&#8217; n&#8217;est pas envoyé à la fonction &#8216;f&#8217;, &#8216;a&#8217; est quand meme défini, et a la valeur null, dans le corps de la fonction. En exploitant cela, on peut modifier notre méthode de tri pour obtenir la suivante :</p>
<pre class="prettyprint">mySort = function(l, reverse){
    l.sort();
    if(reverse) l.reverse();
    return l;
};
>>> mySort([2,4,3])
[2,3,4]
>>> mySort([2,4,3], "reverse")
[4,3,2]</pre>
<p>A noter qu&#8217;ici, la variable reverse est utilisé comme un flag : dans l&#8217;exemple on lui donne la valeur &#8220;reverse&#8221;, mais un simple &#8220;true&#8221; aurait suffit ( même si &#8220;reverse&#8221; aide à la lisibilitée du code )</p>
<h3>Utilisation de la variable argument</h3>
<p>Au passage, une autre astuce (un peu plus avancée celle la) concernant les arguments en javascript : dans une fonction, la variable &#8216;arguments&#8217; contient la liste des arguments qui ont été passés.</p>
<p>Très simplement :</p>
<pre class="prettyprint">myTest2 = function(){
    return arguments;
};
>>> myTest2()
null
>>> myTest2(1,2,3)
[1,2,3]</pre>
<p>Et cela marche quelque soient les arguments &#8216;normallement&#8217; définis :</p>
<pre class="prettyprint">myTest2 = function(a,b){
    return arguments;
};
>>> myTest2()
null
>>> myTest2(1,2,3)
[1,2,3]</pre>
<p>Arguments est une liste tout ce qu&#8217;il y a de plus classique : on peut connaitre sa taille avec arguments.length, et on recupère un élement avec arguments[position].</p>
<p>Concretement, cela permet d&#8217;envoyer un nombre variable de paramètres.</p>
<p>Par exemple, on peut envisager une fonction qui additionne un nombre quelconque de variables.</p>
<pre class="prettyprint">Additionner = function(){
    var sum = 0;
    for(var i=0; i < arguments.length; i++){
        sum += arguments[i];
    }
    return sum;
};
>>> Additionner()
0
>>> Additionner(1,2)
3
>>> Additionner(1,2,3)
6
>>> Additionner(1,2,3,6,12,48)
72</pre>
<p>On constate bien qu&#8217;on peut passer un nombre variable de paramètres, et que le résultat de la méthode est la somme de tous.</p>
    ]]></content:encoded>
			<wfw:commentRss>http://wayofspark.com/2008/07/23/javascript-et-les-arguments-optionnels/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bien connaitre le type d&#8217;une variable javascript : les limites de typeof</title>
		<link>http://wayofspark.com/2008/07/17/bien-connaitre-le-type-dune-variable-javascript-les-limites-de-typeof/</link>
		<comments>http://wayofspark.com/2008/07/17/bien-connaitre-le-type-dune-variable-javascript-les-limites-de-typeof/#comments</comments>
		<pubDate>Thu, 17 Jul 2008 13:39:23 +0000</pubDate>
		<dc:creator>Spark</dc:creator>
				<category><![CDATA[Dev]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://wayofspark.com/?p=3</guid>
		<description><![CDATA[Lorsqu&#8217;on commence à faire du javascript, il arrive forcement un moment ou l&#8217;on à besoin de connaitre le type d&#8217;une variable avec laquelle l&#8217;on travaille. Cela peut être par exemple pour du passage de paramètres multitypés, ou lors de l&#8217;utilisation de paramètres optionnels, Ou l&#8217;ont a parfois besoin de vérifier ce qui a réellement été [...]]]></description>
			<content:encoded><![CDATA[<p>Lorsqu&#8217;on commence à faire du javascript, il arrive forcement un moment ou l&#8217;on à besoin de connaitre le type d&#8217;une variable avec laquelle l&#8217;on travaille. Cela peut être par exemple pour du passage de paramètres multitypés, ou lors de l&#8217;utilisation de paramètres optionnels, Ou l&#8217;ont a parfois besoin de vérifier ce qui a réellement été passé dans les args.</p>
<p>En recherchant sur google, on tombe vite sur ce qui semble être la solution au problème : en effet, javascript dispose d&#8217;une méthode typeof, retournant une string identifiant le type de l&#8217;élément.</p>
<p>exemples :</p>
<pre class="prettyprint">>>> typeof 1
"number"
>>> typeof "hello"
"string"
</pre>
<p>Jusque la, tout va bien. Cependant, les surprises arrivent dès qu&#8217;on pousse les tests un peu plus :</p>
<pre class="prettyprint">>>> typeof [1,2,3]
"object"
</pre>
<p>Tiens, il considère ma liste comme un objet !</p>
<pre class="prettyprint">>>> typeof new Date()
"object"
</pre>
<p>Et les dates aussi !</p>
<pre class="prettyprint">>>> typeof null
"object"
</pre>
<p>Même null est considéré comme étant du type object&#8230;<span id="more-3"></span></p>
<p>En effet, l&#8217;opérateur typeof n&#8217;identifie que les types suivants :</p>
<pre class="prettyprint">"number"
"string"
"function"
"boolean"
"object"
</pre>
<p>Dans la pratique, on a besoin de pouvoir faire la différence entre une liste et un objet, ou de savoir si un paramètre est une date, ou si le retour d&#8217;une méthode est une erreur, par exemple.</p>
<p>La solution consiste donc à bricoler sa propre méthode typeof, pour avoir une identification plus précise des variables. Concrètement, pour identifier un type, on va chercher une bidouille sur la variable à chaque fois.</p>
<p>Par exemple :</p>
<p>Pour les dates c&#8217;est très simple, on regarde si le constructeur est bien &#8216;Date&#8217;.</p>
<pre class="prettyprint">if( var.constructor==Date) // it's a date.</pre>
<p>Pour les listes, on pourrait faire pareil ( regarder si le constructeur est bien &#8216;Array&#8217; ), cependant cela peut poser problème dans certains cas. les selecteurs jQuery, par exemple, sont des listes (on peut faire selecteur[0]), mais sont crées à partir du constructeur object.<br />
Pour les identifier, on vérifie donc à la place la présence d&#8217;un attribut &#8216;length&#8217; sur la variable testée</p>
<pre class="prettyprint">if (el.length) // it's a list</pre>
<p>Pour null, on fait juste un test avec la variable null !</p>
<pre class="prettyprint">if (var==null) // it's null !</pre>
<p>Il reste deux autres pseudotypes, moins utilisés, mais qu&#8217;il peut être tout de même utile de dissocier :</p>
<p>Les erreurs (utile en cas de retour dans un catch par exemple)<br />
La classe erreur est spécifique au navigateur (evidemment), cependant, sous tous, elle dispose toujours de deux attributs : &#8216;message&#8217; et &#8216;name&#8217;. On verifie donc la présence de ces deux attributs, et pour bien faire, on vérifie bien la présence de &#8220;Error&#8221; dans l&#8217;attribut nom.</p>
<pre class="prettyprint">if(el.message!=null &amp;&amp; el.name!=null &amp;&amp; el.name.search("Error")>-1) return 'error';</pre>
<p>Et pour finir, les noeuds DOM. La aussi, c&#8217;est de la bidouille : on verifie l&#8217;existence d&#8217;un attribut nodeName ou tagName sur la variable.</p>
<pre class="prettyprint">if(el.nodeName || el.tagName) return 'node'; // it's a node</pre>
<p>Ce qui donne la méthode suivante :</p>
<pre class="prettyprint">/**
* Return 'advanced' type for an element
* Type can be of :
*  - 'null'
*  - 'string'
*  - 'number'
*  - 'boolean'
*  - 'function'
*  - 'list'
*  - 'node'
*  - 'date'
*  - 'error'
*  - 'object'
* @param el
**/
typeOf = function(el){
var elType = typeof el;

// null type
if(el==null) return 'null';

// basic types : number, string, function
if(elType=='number'||elType=='string'||elType=='function'||elType=='boolean')
    return elType;

// date
if(el.constructor==Date) return "date";

// domElem
if(el.nodeName || el.tagName) return 'node';

// list
if(el.length) return 'list';

// error
if(el.message!=null &amp;&amp; el.name!=null &amp;&amp; el.name.search("Error")>-1) return 'error';

// object
return 'object';
}
</pre>
<p>Et voila, une fonction typeOf qu&#8217;elle est mieux que l&#8217;originale !</p>
<pre class="prettyprint">>>> typeOf([1,2,3])
'list'
>>> typeOf(null)
'null'
>>> typeOf(document.body)
'node'
>>> typeOf(new Date())
'date'
</pre>
<p>Et les type originels sont identifiés aussi :</p>
<pre class="prettyprint">>>> typeOf(1)
'number'
>>> typeOf('hello')
'string'
>>> typeOf(String)
'function'
>>> typeOf(true)
'boolean'
</pre>
<p>Voila, comment gagner pas mal de temps sur les verifs avec une méthode de 10 lignes !</p>
    ]]></content:encoded>
			<wfw:commentRss>http://wayofspark.com/2008/07/17/bien-connaitre-le-type-dune-variable-javascript-les-limites-de-typeof/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
