<?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>David Pratt &#187; javascript</title> <atom:link href="http://daipratt.co.uk/tag/javascript/feed/" rel="self" type="application/rss+xml" /><link>http://daipratt.co.uk</link> <description>Concerned about Website Construction &#38; SEO</description> <lastBuildDate>Thu, 17 May 2012 19:14:00 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <item><title>Using FB.api to make a full post to a users wall</title><link>http://daipratt.co.uk/using-fb-api-to-make-a-full-post-to-a-users-wall/</link> <comments>http://daipratt.co.uk/using-fb-api-to-make-a-full-post-to-a-users-wall/#comments</comments> <pubDate>Sat, 25 Sep 2010 22:43:43 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[facebook]]></category> <category><![CDATA[javascript]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=1367</guid> <description><![CDATA[The JavaScript snippet you need to make a full wall post (including image) to a users wall using the Facebook JavaScript API.]]></description> <content:encoded><![CDATA[<p>I just thought I&#8217;d make another quick post about the Facebook Graph API seen as there seems to be so little documentation and examples for it.  The below example shows you how to make a full wall post with message, name, description, link, picture and caption to the wall of a Facebook user using JavaScript to call the <a
href="http://developers.facebook.com/docs/reference/javascript/FB.api">Facebook FB.api</a>.</p><p>So, assuming that you have an authenticated session, here&#8217;s what you need to do:</p><pre class="brush: javascript">
var params = {};
params['message'] = 'Message';
params['name'] = 'Name';
params['description'] = 'Description';
params['link'] = 'http://apps.facebook.com/summer-mourning/';
params['picture'] = 'http://summer-mourning.zoocha.com/uploads/thumb.png';
params['caption'] = 'Caption';
&nbsp;
FB.api('/me/feed', 'post', params, function(response) {
  if (!response || response.error) {
	alert('Error occured');
  } else {
	alert('Published to stream - you might want to delete it now!');
  }
});
</pre><p>If you do this right you should get something like this appearing:<br
/> <img
src="http://daipratt.co.uk/wp-content/uploads/2010/09/wall-post.png" alt="Showing a full post to the Facebook wall" title="wall-post" width="536" height="157" class="alignnone size-full wp-image-1375" /></p><p>Spamtastic.</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/using-fb-api-to-make-a-full-post-to-a-users-wall/feed/</wfw:commentRss> <slash:comments>15</slash:comments> </item> <item><title>Calculate text width and height with JavaScript</title><link>http://daipratt.co.uk/calculate-text-width-and-height-with-javascript/</link> <comments>http://daipratt.co.uk/calculate-text-width-and-height-with-javascript/#comments</comments> <pubDate>Thu, 22 Apr 2010 08:43:06 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[css]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[ui]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=1123</guid> <description><![CDATA[A tutorial that shows you how to measure the height and width of a text element using JavaScript.]]></description> <content:encoded><![CDATA[<p>Occasionally when putting together an advanced layout it&#8217;s necessary to have a level of control over the UI that can&#8217;t be achieved with CSS alone.</p><p>One situation might be in displaying a place name. Say for instance that place name had to be rendered in block that has a width of 200px, with a height that can flex as necessary to accomodate the content. This won&#8217;t be a problem in 99.9% of situations, but what happens if the place name is Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch?! Yes this place <a
href="http://maps.google.co.uk/maps?f=q&#038;source=s_q&#038;hl=en&#038;geocode=&#038;q=Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch&#038;sll=53.800651,-4.064941&#038;sspn=22.383401,67.631836&#038;ie=UTF8&#038;hq=&#038;hnear=Llanfair+Pwllgwyngyll,+Gwynedd,+United+Kingdom&#038;ll=53.223096,-4.206047&#038;spn=0.17636,0.528374&#038;z=12" target="_blank">does exist</a>! In cases like this you might want to apply a special class name, or maybe dynamically adjust the font-size so that it fits within the allowed container. The consequences of not defending against this situation might be that the layout behaves unpredicatably, breaks, or perhaps some of the word could be hidden by the overflow property in the CSS being set to hidden or something.</p><p>So, should you find yourself in a situation where you need to measure the height and width of a text element, this code might help you:</p><h5>HTML</h5><pre class="brush:php">
&lt;p id="place-name"&gt; Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch&lt;/p&gt;
</pre><h5>CSS</h5><pre class="brush:css">
#place-name{
    position: absolute;
    height: auto;
    width: auto;
}
</pre><h5>JavaScript</h5><pre class="brush:javascript">
var oPlaceName = document.getElementById("place-name");
if (oPlaceName){
	var iHeight = oPlaceName.clientHeight + 1;
	var iWidth = oPlaceName.clientWidth + 1;
	if (iWidth &gt; 200){
		//Deal with the long text.
	}
}
</pre><p>I have prepared a <a
href="/examples/text-width.html" target="_blank">quick standalone example</a> should you want to see this in action.</p><p>A place name might have been a bad example, but it could have quite easily have been any other type of field who&#8217;s length or height you might want explicit control over. Other applications of this that I can think of quickly could be adjusting the font-size of headings so that they never wrap, perhaps adjusting letter spacings so that they have aligned edges, or whatever else the designers .psd file shocks you with! With a clever implementation, this sort of thing could be achieved without the user even noticing, but that&#8217;s a job for someone else!</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/calculate-text-width-and-height-with-javascript/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>Always cache the length property in for loops when using JavaScript</title><link>http://daipratt.co.uk/always-cache-the-length-property-in-for-loops-when-using-javascript/</link> <comments>http://daipratt.co.uk/always-cache-the-length-property-in-for-loops-when-using-javascript/#comments</comments> <pubDate>Tue, 26 Jan 2010 10:13:22 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[performance]]></category> <category><![CDATA[recursion]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=1081</guid> <description><![CDATA[Well, you don't have to, but it helps a smidgen when it comes to performance...]]></description> <content:encoded><![CDATA[<p>To speed up <i>for loops</i> in JavaScript you should always look to cache the <i>length property</i> so that the value of this doesn&#8217;t have to be recalculated on every iteration of the loop.  There are a couple of ways to do this, the first and most obvious way is to calculate the array length outside of the loop e.g.</p><pre class="brush: javascript">
var l = bigArray.length;
for(var i = 0; i &lt; l; i++){
	//Do stuff
}
</pre><p>Another less well known way is to cache the length property in the for loop decleration e.g.</p><pre class="brush: javascript">
for(var i = 0, l = bigArray.length; i &lt; l; i++){
	//Do stuff
}
</pre>]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/always-cache-the-length-property-in-for-loops-when-using-javascript/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Using the logical OR operator in setting variables</title><link>http://daipratt.co.uk/using-the-logical-or-operator-in-setting-variables/</link> <comments>http://daipratt.co.uk/using-the-logical-or-operator-in-setting-variables/#comments</comments> <pubDate>Mon, 11 Jan 2010 09:58:01 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[javascript]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=994</guid> <description><![CDATA[A technique that sets a variable by testing the result of the logical OR operator based on the existence of the two conditions.]]></description> <content:encoded><![CDATA[<p>If you ever find yourself setting a variable based on the existence of an object property or variable, and write tests similar to [Edit: assuming that the Object <i>object</i> is known to exist.]:</p><pre class="brush: javascript">
if (object.property){
	var foo = object.property;
}else{
	var foo = "foo";
}
</pre><p>Or:</p><pre class="brush: javascript">
var foo = "foo";
if (object.property){
	foo = object.property;
}
</pre><p>Then there is more elegant way to achieve this by using the logical OR (||) operator in setting the variable.  The same result as above can be achieved by this line of code:</p><pre class="brush: javascript">
var foo = object.property || "foo";
</pre><p>What this is in effect doing is testing the result of the logical OR operator based on the existence of the two conditions i.e. object.property and &#8220;foo&#8221;. As &#8220;foo&#8221; will always resolve to true because it exists, it is just down to the ambiguity of object.property to determine the output i.e. if object.property exists, then foo will take the value of object.property, otherwise it will adopt the value &#8220;foo&#8221;.</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/using-the-logical-or-operator-in-setting-variables/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>Using a function&#8217;s arguments array in JavaScript</title><link>http://daipratt.co.uk/using-a-functions-arguments-array-in-javascript/</link> <comments>http://daipratt.co.uk/using-a-functions-arguments-array-in-javascript/#comments</comments> <pubDate>Sun, 29 Nov 2009 11:35:48 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[function]]></category> <category><![CDATA[javascript]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=678</guid> <description><![CDATA[A tutorial that explains how to access a functions arguments array.]]></description> <content:encoded><![CDATA[<p>When you pass parameters into a function, there is an easy way to retrieve them without first pre-defining them.  There is something called the <em>arguments array</em> array which allows you to access the information passed into a function.  Now, because you can determine the size of the arguments array it allows you to do useful things like:</p><pre class="brush: javascript">
function sum() {
  var total = 0;
  for (var i=0; i < arguments.length; i++) {
    total = total + arguments[i];
  }
  return total;
}
sum(5,4,3); //returns 12
</pre><p>What this function does is take any number of parameters and then add them together.</p><p>You can also do the <em>arguments.length</em> technique in reverse by using the length method against the function. This will then give you the number of variables that are expected by a function. For example:</p><pre class="brush: javascript">
function sum(x, y, z){
    return x + y + z;
}
console.log(sum.length); // returns 3, as that is the number of expected parameters.
</pre><p>I can't say I use either of these techniques a great deal, but they are useful to know nonetheless!</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/using-a-functions-arguments-array-in-javascript/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Debugging JavaScript the easy way</title><link>http://daipratt.co.uk/debugging-javascript-the-easy-way/</link> <comments>http://daipratt.co.uk/debugging-javascript-the-easy-way/#comments</comments> <pubDate>Sat, 21 Nov 2009 13:08:24 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[debugging]]></category> <category><![CDATA[javascript]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=621</guid> <description><![CDATA[A function that tests for the existence of the console.log method, and if it doesn't exist, instead calls alert(). Handy when you're testing in different browsers that don't all have Firebug installed.]]></description> <content:encoded><![CDATA[<p>If you use the <a
href="https://addons.mozilla.org/en-US/firefox/addon/1843">firebug</a> function <i>console.log()</i> liberally throughout your javascript when you&#8217;re developing, you&#8217;ll know it&#8217;s a bit of a pain when you want to test your code in a browser that hasn&#8217;t got a version of firebug enabled (as the non-existence of the <i>console</i> object will prevent the javascript from working properly).</p><p>I wrote this simple bit of code to get around that problem:</p><pre class="brush: javascript">
if(!window.console){
	var console = {
		log : function(msg){
			alert(msg);  //You could leave this statement out if you wanted the debugging to be silent when firebug isn't enabled
		}
	}
}
</pre><p>All it does is test for the existence of the <i>console</i> object, and if it doesn&#8217;t exist use the classic debuggers friend, <i>alert()</i>. You could extend this to incorporate <i>console.debug()</i> etc. but if you&#8217;re going to go to them lengths, then you may as well just use <a
href="http://getfirebug.com/lite.html">firebug lite</a>.</p><p>Another way I&#8217;ve seen described in the past for manging this problem is to use a <i>log()</i> function that might look something like:</p><pre class="brush: javascript">
function log(msg) {
	if(console){
		console.log(msg);
	}else{
		alert(msg);
	}
}
log("debug message");
</pre><p>Another way would be to do it the other way around and overwrite the alert function with <i>console.log</i> if it exists:</p><pre class="brush: javascript">
if ( window.console ){
	if ( window.console.log ) {
		window.alert = console.log;
	}
}
</pre><p>All three methods mentioned above are a lot more effective than commenting out every instance of <i>console.log</i> in your code!  Come on, we&#8217;ve all done it&#8230;</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/debugging-javascript-the-easy-way/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Notes about combining jQuery and Greasemonkey</title><link>http://daipratt.co.uk/notes-about-combining-jquery-and-greasemonkey/</link> <comments>http://daipratt.co.uk/notes-about-combining-jquery-and-greasemonkey/#comments</comments> <pubDate>Thu, 05 Nov 2009 16:10:32 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[greasemonkey]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[jquery]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=595</guid> <description><![CDATA[Greasemonkey doesn't inherit the jQuery library if it is just loaded onto the web page as normal. To use jQuery methods from GreaseMonkey code, you need to do this bit of coding magic...]]></description> <content:encoded><![CDATA[<p>Having just written my first Greasemonkey script in a while, I thought I might share some of my learning&#8217;s!</p><h4>Include jQuery by using the @require statement</h4><p>Greasemonkey doesn&#8217;t inherit the jQuery library if it is just loaded onto the web page as normal, you need to figure out a way of allowing your Greasemonkey script to use it another way.  If I had read the Greasemonkey docs from the off, I would have stumbled across the correct method within about 5 minutes, but I didn&#8217;t, I just dived straight on in and it took a lot longer&#8230;</p><p>To add jQuery, include the @require line in your script header.  This needs to be done before you install the script and cannot be done retrospectively.</p><pre class="brush: javascript">
// ==UserScript==
// @name          Awesome Tool
// @namespace     http://daipratt.co.uk
// @description   Top Secret
// @include       http://daipratt.co.uk/*
// @require       http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js
// ==/UserScript==
</pre><h4>Make sure that your Greasemonkey script ends in <em>.user.js</em></h4><p>If it doesn&#8217;t, you&#8217;ll spend ages wondering why it won&#8217;t let you install a local script.</p><h4>Store session data</h4><p>You don&#8217;t need an elaborate method of storing data for retrieval between sessions and pages, there are a pair of functions built into Greasemonkey that do the job nicely:</p><pre class="brush: javascript">
//Sets a key value pair that Greasemonkey should store
GM_setValue(key, value);
//Retrieves a value, given an existing key
var v = GM_getValue(key);
</pre>]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/notes-about-combining-jquery-and-greasemonkey/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Defensive coding in JavaScript with Namespacing</title><link>http://daipratt.co.uk/defensive-coding-in-javascript-with-namespacing/</link> <comments>http://daipratt.co.uk/defensive-coding-in-javascript-with-namespacing/#comments</comments> <pubDate>Fri, 02 Oct 2009 10:05:42 +0000</pubDate> <dc:creator>daipratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[defensive]]></category> <category><![CDATA[javascript]]></category> <category><![CDATA[namespacing]]></category> <guid
isPermaLink="false">http://localhost/wordpress/?p=184</guid> <description><![CDATA[A tutorial on how to go about namespacing your JavaScript, plus a list of some of the benefits that you get from doing so.]]></description> <content:encoded><![CDATA[<p>Having learnt some harsh lessons early on in my career about the drawbacks of using generic/common function names, such as <i>init</i> or <i>basket</i> for instance &#8211; I once took out important &#8220;add to basket&#8221; functionality on a major retail website due to a conflicting function name that only manifested itself in production. Not good.</p><p>Since then, I have embraced JavaScripts namespacing ability (along with anonymous functions) to complement the defensive style that I quickly felt the need to adopt! I think that coding defensively is especially important because it is often impossible to conceive what the future business requirements of a site will be, what client side code could be thrown at it, or the caliber of developer working on it. The last thing you want is a developer from the marketing department innocuously dropping a “cool” image rotating script site wide in the document &lt;head&gt; and taking out business critical code as a result. It’s embarrassing for the guilty developer, but I think more so for the senior guy who should’ve coded more defensively in the first place.</p><p>This may or may not work for you, but I namespace everything to mitigate the chances of collision of functions, variables, objects, anything bar the root global variable name, from any new code that follows later, or more broadly <abbr
title="other peoples code">OPC</abbr>.</p><p>Anyway, a namespace essentially provides a container for all of your code to sit within.  At its simplest, it can be defined like so:</p><pre class="brush: javascript">
var myFirstNamespace = {};
</pre><p>This can then be extended in any manner you please. For example:</p><pre class="brush: javascript">
//Extend myFirstNamespace
myFirstNamespace.helloWorld= function() {
	console.log('Hello World!');
};
&nbsp;
//Use the myFirstNamespace properties
myFirstNamespace.helloWorld();
</pre><p>This would then write the following into your Fire Bug console:</p><pre class="brush: text">
Hello World!
</pre><p>Easy peasy.</p><p>As a real world example, at Bounty, everything new went into a <i>bounty</i> namespace, which in turn had things like <i>bounty.utils</i>, <i>bounty.ui</i> to separate the various functions that were held within.  Here&#8217;s a skeleton namespace that might make it easier to understand what I mean:</p><pre class="brush: javascript">
var bounty = {
	init : function(){
		//Initialise functions within the bounty namespace
		bounty.advert.fInit();
		bounty.ui.fInit();
		bounty.utils.fInit();
	},
	advert : {
		fInit : function(){
			//Initialise bounty.advert
		},
		fAdvertFunction1: function(){
			//An advert function
		},
		fAdvertFunction2: function(){
			//Another advert function
		}
	},
	ui : {
		fInit : function(){
			//Initialise bounty.ui
		},
		tabBox : {
			fInit : function(){
				//Initialise bounty.ui.tabBox
			}
		}
	},
	utils : {
		fInit : function(){
			//Initialise bounty.utils
		}
	}
};
$(document).ready(function(){
	//Initiliase bounty.
	bounty.init();
});
</pre><p>I find that this style of coding helps in enforcing a structure to the code, which is particularly helpful when there are large quantities of it, and when it comes to debugging.  Another positive side effect is that if your chosen code editor supports code folding, then you can quickly collapse everything and get a very clear architectural overview of what it does without having to trace your way through functions to understand what&#8217;s going on.</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/defensive-coding-in-javascript-with-namespacing/feed/</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>You should probably put that in a function&#8230;</title><link>http://daipratt.co.uk/you-should-probably-put-that-in-a-function/</link> <comments>http://daipratt.co.uk/you-should-probably-put-that-in-a-function/#comments</comments> <pubDate>Mon, 14 Sep 2009 10:25:50 +0000</pubDate> <dc:creator>David Pratt</dc:creator> <category><![CDATA[Tech]]></category> <category><![CDATA[abstraction]]></category> <category><![CDATA[javascript]]></category> <guid
isPermaLink="false">http://daipratt.co.uk/?p=512</guid> <description><![CDATA[A few pointers on making your JavaScript code more readable, amongst other things.]]></description> <content:encoded><![CDATA[<p>I&#8217;ve worked on a lot of sites in my time, most of which have comprised of a large body of code that has been developed over a period of years.  What seems to be a common theme to me is the difference between the sometimes lack of craftsmanship in the JavaScript code compared to the back-end languages.  I&#8217;m sure there are many reasons for this, but I think that it is largely due to the fact that the need for good front-end engineering has only been widely recognised since the web standards movement really began to take hold a few years ago.  Prior to this when JavaScript was unfashionable, I&#8217;m sure that the majority of the brightest graduates leaving university were swayed towards the more serious languages (.Net, Java etc.) because that was where the money was, leaving the door open just enough for the copy and paste brigade to gain a foothold.</p><p>Anyway, I intend this post to be the first in a series of posts about where some JavaScripters go wrong with the basics.</p><p>So, pet hate number 1 is&#8230; <em>When the same line or sequence of code is repeated in a number of locations across a file</em>.  Here&#8217;s what I mean:</p><pre class="brush: javascript">
//Calculate grade
grade = (userTotal / maxPossible) * 100;
grade = Math.round(grade);
</pre><p>Fairly simple I&#8217;m sure you&#8217;ll agree &#8211; the code is calculating some sort of grade and then rounding it off.  Nothing wrong with this in itself, but we can make it cleaner by abstracting it into a function:</p><pre class="brush: javascript">
function calculateGrade(userTotal){
    grade = (userTotal / maxPossible) * 100;
    grade = Math.round(grade);
    return grade;
}
</pre><p>You could even do it on one line if you really wanted too:</p><pre class="brush: javascript">
function calculateGrade(userTotal){
    return Math.round((userTotal / maxPossible) * 100);
}
</pre><p>The original line of code can now be replaced with something a lot more readable:</p><pre class="brush: javascript">
grade = calculateGrade(userTotal);
</pre><p>If this were just in one place in your code then fine, no massive benefit has been gained bar a bit of readability, but if this same calculation is carried out in multiple places, then the benefits really begin to emerge:</p><ul><li>If the grade calculation changes, then it only needs to be amended in one place.</li><li>It avoids duplicate code, and uses less of it.</li><li>Improves performance.</li><li>Reduces complexity, and also isolates it.</li><li>The program becomes a little more self-documenting.</li><li>Enables code re-use.</li></ul><p>If I sat down and thought about it, I&#8217;m sure I could reel off many more reasons, but even for just these few it has got to be worth investing the time to understand the basics of functions and abstraction.</p> ]]></content:encoded> <wfw:commentRss>http://daipratt.co.uk/you-should-probably-put-that-in-a-function/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
