<?xml version='1.0' encoding='ISO-8859-1' ?>

<rss version='2.0'>
	<channel>
		<title>Mitya.co.uk | Javascript and general front-end dev blog</title>
		<link>http://www.mitya.co.uk</link>
		<webmaster>rss@mitya.co.uk</webmaster>
		<lastBuildDate>2011-09-21 19:44:00</lastBuildDate>
		<image>
			<url></url>
			<link>http://www.mitya.co.uk</link>
		</image>
		<description></description>
		<ttl>5</ttl>
		<language>en-gb</language>

		<item>
			<title>Numberfy: add line numbers to your textareas</title>
			<link>http://www.mitya.co.uk/blog/2012/Jan/Numberfy-add-line-numbers-to-your-textareas-198</link>
			<description>Ever wished textareas had native support for line numbers?

I, and doubtless the developers behind the many JSFiddle-esq sites out there these days, have.

So I've built a jQuery plugin that does precisely that. Just target the textarea(s) you want to add line number support to via a jQuery selector, call the numberfy method, and that's it.



[VISIT THE LINK FOR THE CODE].

This tuned out to be an interesting little thing to build. The most challenging part, obviously, was getting the numbers to appear at the right positions vertically, to take into account line wrapping.

The solution here is simple but effective; on every keypress in the textarea, the textarea's current value is split into lines, then one by one each line is added to the clone and its offset height measured.

That tells us how tall the line is, including wrapping, and tells us therefore where to position the line number.

It's worth pointing out that the clone is not actually a clone of the textarea - it's aElt;p> tag; the reason is the clone needs to have fluid height, so we can read its offset height. A textarea's dimensions are never fluid.

[h]IE, sod off[/h]

It doesn't currently work correctly in IE. This is because I discovered a little-known 'bug' in IE whereby text within textareas wraps differently from text in other areas - even where they have the same word-wrap / white-space CSS properties.

I moaned about it on Stack Overflow, and the consensus so far seems to be there's nothing that can be done about it. I'll keep looking at this.



Enjoy.</description>
			<pubDate>2012-01-23 18:31:00</pubDate>
		</item>
	
		<item>
			<title>JSON and PHP: formatting and validating</title>
			<link>http://www.mitya.co.uk/blog/2012/Jan/JSON-and-PHP-formatting-and-validating-196</link>
			<description>[h]Formatting JSON to look all lovely[/h]

It's always a happy day when I manage to use JSON in PHP. As a JS developer, it sort of feels like I'm marrying the two technologies. Take that, serialised arrays - I'm using JSON.

PHP, of course, has support for encoding and decoding JSON via json_encode() and json_decode() respectively. What it can't do natively, though, is format JSON.

Why would you want to format JSON in PHP to make it look all nice and indented? Well, if the system you're building uses JSON for a config file, and you want users to be able to edit that config file within the system, in a textarea, say.

I then found this function, which largely does the job.

It can, however, get the indentation wrong sometimes. Also, it can leave whitespace at the end of lines. So I extended it slightly. The following three snippets should be inserted just before the final return statement.

Firstly, let's clear any whitespace left at the end of lines.
[VISIT THE LINK FOR THE CODE].

Next, let's fix the indentation. What I noticed was that the script was indenting lines containing closing brackets/braces precisely double what it should be - so four tabs instead of two, for example. So, the following halves each case.

[VISIT THE LINK FOR THE CODE].

Note I'm using a callback on preg_replace() - this gives me greater control over the nature of my replacements. preg_replace() automatically forwards to my callback one argument - an array of the match. As ever, key 0 in the array contains the whole match and any subsequent keys contain any sub-matches my pattern looked for.

Lastly, either the script or (more probably) my hacks above end up killing some of the line breaks, so let's restore them.

[VISIT THE LINK FOR THE CODE].

Et voila - nicely formatted JSON.

[h]Make sure your JSON's valid[/h]

JSON and JavaScript Object Notation are not always the same thing. How so? Well, this is valid JS but INvalid JSON:

[VISIT THE LINK FOR THE CODE].

...because the JSON spec demands that a) property names are quoted; b) property names and strings must be encased in double, not single quotes.

So if you end up with invalid JSON, how will you know? PHP >= 5.3 defines json_last_error(), which returns a flag saying what went wrong.

Confusingly, it returns something even if nothing went wrong - JSON_ERROR_NONE. It does not return false, so it is insufficient to check the validity of JSON with:

[VISIT THE LINK FOR THE CODE].

Instead, the last line should be:

[VISIT THE LINK FOR THE CODE].

[h]PHP versions prior to 5.3[/h]

If you're running PHP prior to v.5.3, you won't have json_last_error(). Instead, you can simply check the truthy/falsy value of json_decode(), so:

[VISIT THE LINK FOR THE CODE].

Obviously this approach is more crude and won't tell you what went wrong - just that something did.

If you're looking for somewhere to host your PHP, whether Linux or Windows hosting, it always pays to make use of a good web hosting review site to find the right web hosting provider. This is a particularly good one, especially their WordPress hosting search page if you’re still on your way finding a suitable home for your WordPress blog.</description>
			<pubDate>2012-01-04 21:05:00</pubDate>
		</item>
	
		<item>
			<title>Being Firebug, pt2: which rules, which elements?</title>
			<link>http://www.mitya.co.uk/blog/2011/Dec/Being-Firebug-pt-which-rules-which-elements-195</link>
			<description>Ever wondered how Firebug, Dragonfly and other debug tools manage to detect which styles apply to an element, whether they're currently active, what stylesheet (if any) they're coming from, and other such info?

In this second part of a two-part blog post, I'll be showing you how to do just that.

[h]You read part 1, right?[/h]

Before we begin, make sure you read part one, which I posted last week, as this post continues from there and assumes you understood what I was waffling on about there.

[h]I read it - so now what?[/h]

So you read part one - therefore you understand how Javascript can read the CSS rules and styles coming into a page from stylesheets, and how it can also read 'computed styles' on a given element.

Now we're going to look at how to see which CSS rules apply to a given element - and which of its styles are active or have been overridden.

[h]Detecting if a rule applies to an element[/h]

This would be horrible to do in native Javascript. Possible, but horrible. Thankfully, an unsuspecting jQuery method, .is(), is going to save us a hell of lot of code writing.

If you're not familiar with .is(), it returns true or false based on whether the element(s) on the jQuery stack matches the selector you pass to it. So for example:

[VISIT THE LINK FOR THE CODE].

Pretty simple. So how does that help with what we're doing? Well, as we saw in part one, Javascript's DOM CSS Rule object allows us to access not only the styles of a particular rule but also the selector text, i.e. the part before the {.

If we pass that to .is() on the element we're interested in, we find out if the rule applies to that element. Pretty neat, eh? Observe.

[VISIT THE LINK FOR THE CODE].

Note I'm skipping the validation - i.e. checking that el actually finds an element with ID 'myElement', and that there really is a stylesheet[0] - just to keep the code succinct, but you'd obviously want to check for these things in a real-world environment.

If you console.log our rulesThatApply array, you'll see that it contains the selector text of the rules that apply to our element, just as we'd hoped. So far, so good.

[h]In case you missed it...[/h]

See what we did there? See how the .is() method is they key? The method, as I mentioned above, returns true or false depending on whether the element(s) in the jQuery stack matches - in other words, is targetable by - the selector you pass to the method.

That is NOT to say that the CSS rule's selector text must match exactly the jQuery selector we use to target the element (if we use jQuery at all; in the above code, I target an element natively) - rather, that it must ultimately select the same element. So for example:

[VISIT THE LINK FOR THE CODE].

[VISIT THE LINK FOR THE CODE].

When our code runs, and the loop gets to that rule, we are effectively asking:

[VISIT THE LINK FOR THE CODE].

[h]Detecting if a style is active or overridden[/h]

Detecting what rules are talking to an element is one thing. But that does not mean, of course, that all the styles of a particular rule are active on the element - they may have been overridden by other rules or by inline styles.

The key here is to test the implicitly-set CSS value of the style against the computed - i.e. current - value of the style. If they match, it means the CSS style is still in effect. It they don't, it has been overridden.

Simple, right? Well, pretty much, but there are a few pitfalls.

First, colours. You probably set colours in your CSS via HEX syntax - however most browsers return computed colours in RGB format. So if you set #f90 in your CSS, when you read it back from the computed styles you'll be told rgb(255, 153, 0).

Secondly, you'll want to harmonise string format before attempting comparison. The most obvious example here is the dashes-vs-camel-case thing going on between CSS and JS - i.e. text-decoration, but textDecoration in JS.

So, let's get to work. For demo purposes, let's work with just one CSS rule and its styles.

[VISIT THE LINK FOR THE CODE].

The first two parts of that are exactly the same as we did in the code earlier in this post. The last line simple grabs the first rule of the stylesheet. This returns to us a DOM CSS Rule object. This is an object of the various styles that the rule sets, e.g. color.

Let's iterate over these styles and, for each, compare it to the current, computed style. As I mentioned above, we'll need to harmonise the values so they are comparable. The most complex part of this is colours - we'll convert them all to HEX format.

[VISIT THE LINK FOR THE CODE].

You might be wondering where that RGBToHex function comes from. Well, I wrote it - and here it is, so you'll need this, too.

[VISIT THE LINK FOR THE CODE].

That function is beyond the scope of this article, but hopefully it's fairly simple in what it does. Basically, you feed it an RGB colour (e.g. rgb(255, 0, 0) or even just 255,0,0) and it returns the colour in HEX format. If the colour is already in HEX format it merely returns what you give it, unchanged.

[h]So, what did we just do?[/h]

Let's look at a few things in that code. As I said, in order to see if a style is active, we need to compare it to the current, computed equivalent. This means harmonising two values:

- Line 7: the name of style, from dashes to camel case, e.g. text-align to textAlign
- Lines 15/16: colours into HEX format, because most browsers return computed colours in RGB format (even if you set them in HEX!)

[h]So there you have it[/h]

A lot to take in, but hopefully you've got an idea of how the likes of Firebug and Dragonfly do their thing.

Oh and do remember that, like all code that deals with the DOM, you'll want to use the code from this post inside a window.onload callback or, if using jQuery, inside a document ready handler.</description>
			<pubDate>2011-12-12 18:27:00</pubDate>
		</item>
	
		<item>
			<title>Being Firebug, pt1: reading CSS in Javascript</title>
			<link>http://www.mitya.co.uk/blog/2011/Dec/Being-Firebug-pt-reading-CSS-Javascript-194</link>
			<description>Ever wondered how Firebug, Dragonfly and other debug tools manage to detect which styles apply to an element, whether they're currently active, what stylesheet (if any) they're coming from, and other such info?

In a two-part post, I'll be looking at how that's done in Javascript. Yes, it's all Javascript.

I find many junior-to-intermediate JS developers are surprised to find out JS has a rich API for this sort of thing (given Javascript's limited API generally).

In this first post I'll be looking at how you read the styles loaded into your page. In the second post, in the coming week, I'll look at how you can then work out which styles apply to a particular element - and whether they're currently active or have been overridden by another style.

[h]The API[/h]

There's two key parts here: one to detect rules and styles from loaded stylesheets (or inline Elt;style> tags), and another to detect current styles - i.e. the current styles active on an element, from whatever source.

The latter are called computed styles - i.e. the current style, from whatever source.

[h]Getting computed styles[/h]

As is often the case, this is a case of Microsoft vs. the rest. Non-IE browsers define a function, getComputedStyle, which accepts two arguments, but you'll nearly always pass only one (more on that later) - the first one - which should be a reference to an element. IE, however, defines an object on each element's prototype, currentStyle, which contains sub-properties for each current style.

Let's get the computed colour of the first paragraph in a page. As ever in a situation like this, where there's differing approaches for different browser, a spot of feature detection is in order:

[VISIT THE LINK FOR THE CODE].

That should be pretty obvious what's happening - if element.currentStyle is supported, we use that - else we use getComputedStyle().

Sidenote: I actually prefer IE's way of doing things here. I know, I know, it's not often you hear a developer say that. But it just seems so much more sensible that, since these properties are, by their nature, dynamic, and not unchangably set at runtime, they live ON the element. The non-IE way of defining a function instead seems at odds with Javascript's prototypal inheritance philosophy. After all, plenty of other dynamic properties live on the elements themselves, in all browsers, such as offsetHeight.

[h]Getting CSS rules/styles[/h]

Javascript has an API for reading the rules and styles of every linked stylesheet or inline Elt;style> tag in your page. It does this through the document.styleSheets object.

[VISIT THE LINK FOR THE CODE].

Each element of the object represents a linked stylesheet or document.styleSheets in your page. Go a level deeper, and you can access the rules and styles within. Again, however, there's differences in the name of this property between IE and the rest: cssRules in non-IE browsers, and rules in IE.

Let's get the total styles for the whole page, into a nice, tidy array in the following format:

[VISIT THE LINK FOR THE CODE].

Hopefully the structure is pretty obvious: an array containing a sub-object for each stylesheet/style tag, which in turn contains its href (or, if inline, simply 'inline') and a rules sub-object, named after the selector text of the rule, and which contains the styles/values themsleves. So let's get it on:

[VISIT THE LINK FOR THE CODE].

Hopefully the comments in that code block make it quite clear what's going on. Essentially, it's a case of rather unprettily drilling down, through a series of nested for loops (urgh...) from the stylesheet to the rules, to the actual styles.

[h]Summary[/h]

So there you have it. Note that you'll need to run the above only once the window (or at least DOM) has loaded, otherwise the browser won't be ready to talk to Javascript about stylesheets just yet.

Look out for the next part in this post, later in the coming week, in which we'll see not only how to detect what styles are present in a page, but which apply to a particular element and whether they're currently active, ala Firebug, Dragonfly and other debug tools.

Oh and be sure to bookmark the Javascript API references for the DOM StyleSheet and DOM CSS rule objects.

Enjoy.</description>
			<pubDate>2011-12-03 20:16:00</pubDate>
		</item>
	
		<item>
			<title>Additions to XML tree; jQuery XML parsing</title>
			<link>http://www.mitya.co.uk/blog/2011/Nov/Additions-to-XML-tree-jQuery-XML-parsing-193</link>
			<description>You may have seen my XMLTree plugin, posted a few weeks ago.

If you'll excuse the trumpet-blowing I do find this plugin among my most useful; I'm working on a number of projects right now that involve XML in the browser, and the ability to visualise it in a traversable tree is quiet satisfying.

New features (all documented on the script page) include:

- callback on resultant HTML - you can now specify a callback function which will be invoked after the tree has been generated. It is automatically passed a DOM reference to the tree ul so you can act on it.

- attributes - can now be ignored, hidden or shown. Hiding them is useful if you plan to traverse or interrogate the tree based on their existence or value, without wanting to show them to the user.

[h]Bug fixes[/h]

This was an interesting one. With XMLTree you can either point it at an XML file for it to load, or manually pass it a well-formed string of XML.

In the latter case, it exploits a well-known (yet somewhat abused) perk of jQuery - that you can pass it a DOM or XML string and it will turn it into a nodeset.

But because this is intended for DOM creation, not XML creation, it assumes you're parsing an HTML document, not XML. The problem? If your XML contains any tags that share their names with any self-closing HTML tags, jQuery renders your XML invalid.

Consider the following example:

[VISIT THE LINK FOR THE CODE].

The output of that will be:

[VISIT THE LINK FOR THE CODE].

...which is obviously not what you'd wanted.

As a fix for this XMLTree now renames (secretly) all of the node names - but restores their original names on output.

Ideally, of course, I wouldn't be lazy and rely on jQuery to parse XML - there are native ways (albeit different ones for different browsers). But for now this fix works just fine.

</description>
			<pubDate>2011-11-24 08:45:00</pubDate>
		</item>
	
		<item>
			<title>BAPS (browser and plugin sniffer)</title>
			<link>http://www.mitya.co.uk/blog/2011/Nov/BAPS-browser-and-plugin-sniffer-192</link>
			<description>BAPS, apart from being an acronym chosen purely for its its puerile humour, stands for browser and plugin sniffer - and I've just posted it in the scripts section.

As promised earlier this week, this is a utility to accurately detect information about the user's environment, such as browser name, version, language and installed plugins.

This is an area that is famously annoying, since different browsers expose different information to the Javascript's native navigator object, which exists to tell developers about the user's environment. Thus, it's never been standardised.

BAPS clears this up, as it caters for browsers' inconsistencies. It caters, for example, with the fact that Opera 11.52 declares itself as Opera 9.8. And for the fact that Chrome declares itself as, er, Netscape.

It sets a global variable, baps, which is an object containing various information about the user's environment, such as browser, version, language and plugins.

In terms of plugins, it detects Flash, WMP and QuickTime, but you can easily extend it to look for more.

</description>
			<pubDate>2011-11-13 17:34:00</pubDate>
		</item>
	
		<item>
			<title>Roundup: animated table sort / browser sniffing</title>
			<link>http://www.mitya.co.uk/blog/2011/Nov/Roundup-animated-table-sort-browser-sniffing-189</link>
			<description>With the exception of Blockster, the most popular script I've ever posted is my animated table sorter.

Which is rather odd, since as far as I'm aware it's buggy. Somehow, though, if the comments and e-mails are anything to go by, loads of people have been able to use it just fine.

Given this unexpected popularity I'm going to attempt to rebuild it in the coming months.

This script is among the top five hardest scripts I've written, so I'll, er, look forward to that.

In other news, stay tuned for my next script, later this week - a browser and plugin sniffer.

Browser sniffing is one of those things that you can't believe there still isn't a standard way of doing. Even jQuery's $.browser utility comes with a load of caveats warning that results might not be as expected.

And it's little wonder. Different browsers declare different, non-standard data in the various properties of the navigator object. Over the years these have led to some amusing revelations; if you ask Chrome what its navigator.appName is you'll get... Netscape. Naturally.

So I've been labouring away on a script that will provide you with something representing a reliable utility for this sort of thing. Not only with regards to detecting browser name but also other info such as language (more on that later...) and plugin support (and on that...).</description>
			<pubDate>2011-11-07 07:04:00</pubDate>
		</item>
	
		<item>
			<title>Annoyances with client-side XSL transformation</title>
			<link>http://www.mitya.co.uk/blog/2011/Oct/Annoyances-with-client-side-XSL-transformation-188</link>
			<description>A current project of mine heavily involves XSL.

XSL is that rare thing: a technology that can run both on the client and on the server.This might be exciting if it wasn't so dubious; the likelihood of browsers and servers implementing a recommendation in equivalent fashion, just seems so unlikely.

That said, XSL does, I must admit, enjoy a pretty decent implementation in the browser, and with few cross-browser issues, too.

Naturally you won't want to be trying it in the likes of IE6 (which runs a very, very stripped-down version of XSL) but if you don't care about IE6, you should be fine.

Today, though, I did hit a snag: where XSL imports are concerned. Specifically, they don't work in Webkit browsers (Safari, Chrome).

This is only a problem when transforming your XSL through Javascript, i.e. within a webpage context - not if you're opening up the XML manually. In the latter case, your imports will work fine.

This is annoying, and it's not at all clear why Google/Apple don't add support for this.

[h]Weirdness in Opera[/h]

As anyone close to me will tell you (or, rather, sigh and then tell you), my browser of choice is Opera. Now Opera does support XSL includes in the context of JS transformation... in a way.

If you load the XSL from a file, any XSL include statements within it will work.

[VISIT THE LINK FOR THE CODE].

If, however, you specify and convert your XSL from a string, not from a file, you can forget about XSL includes.

[VISIT THE LINK FOR THE CODE].

This would appear to be a bug. In both cases, the resultant xml and xsl vars are both typeof == 'XML Document Object'. In other words, they should be equivalent - but only the former approach allows XSL includes.

Looks like I'll be doing my XSL on the server after all.</description>
			<pubDate>2011-10-25 19:37:00</pubDate>
		</item>
	
		<item>
			<title>XML Tree - visualise and traverse your XML</title>
			<link>http://www.mitya.co.uk/blog/2011/Oct/XML-Tree---visualise-and-traverse-your-XML-187</link>
			<description>XMLTree, just posted in the scripts section, is a utility for visualising and traversing XML in tree format.

You point it to an XML file, or manually feed it XML, and it does the rest, turning your nodes into a traversable tree. 

But it's more than that; you can stipulate callbacks to fire when a node is expanded/collapsed and/or clicked. Callbacks are passed certain standard arguments, such as a reference to the node that was clicked and the XPath to it.

Behold! I even made a lovely demo for you involving Nintendo characters:

[DEMO]


new xmltree({
	fpath: '/inc/script_demos/xmltree/xml.xml',
	plusMinCallback: null,
	nodeCallback: null,
	containerSel: '#tree',
	startCollapsed: true
});

[/DEMO]

You can also deep-link to a point or points within the tree, so that, on load, the tree opens at a specific point or points. By extension, this means the tree is refresh-friendly, i.e. it won't forget which nodes were open when you reload the page.

</description>
			<pubDate>2011-10-18 21:49:00</pubDate>
		</item>
	
		<item>
			<title>Fiddler - when debugging needs to go nuclear</title>
			<link>http://www.mitya.co.uk/blog/2011/Sep/Fiddler---when-debugging-needs-to-go-nuclear-185</link>
			<description>Ever met Fiddler? It's a fantastic debugging tool, useful anytime you need to front-end debug on a server you don't currently have write access to.

Sure, you have Firebug and Dragonfly, or whatever your browser of choice calls its debug kit. But in those you can't edit linked files and refresh the runtime environment with those changes. The minute you reload the page, the files are reset.

(Sidenote: Opera has a cool feature whereby, when viewing the source code, you can make changes then 'apply' them, reloading the page with your changes.)

Fiddler acts like a proxy server. It hijacks HTTP requests from your browser (though not all browsers - Opera is unfortunately not supported, it seems) and allows you to server up hacked versions of those files rather than versions fresh from the server.

Its interface is far from intuitive, so I thought I'd post a demo. I hope you find it useful.

[h]1) Download Fiddler[/h]

Download and install Fiddler. If it prompts you after installation to download or upgrade the .NET framework from Microsoft, I found this wasn't necessary.

[h]2) Set things up[/h]

Open up Fiddler. First off, you'll want to disable caching. Go to rules > performance and select Disable Caching. Next up, to tell Fiddler to hijack your HTTP requests henceforth, on the right go to the AutoResponder tab. Check the Enable automatic responses and Unmatched requests passthrough checkboxes.

[h]3) Start logging[/h]

Fiddler will now log all HTTP requests that are made from supported browsers. Try it; go to a page in Firefox, then check back to Fiddler and you'll see all the requests that came through, along with their response codes, MIME types etc.

Tip: to quickly find a file in the list, press ALT+Q (or just focus into the black text field under the list of files) and type ? followed by the partial name of a file to highlight.

[h]4) Here's the clever bit[/h]

OK, so we've got Fiddler logging requests. The next step is to get it to hijack particular requests and instead of returning content from the server, return content from Fiddler that we're going to hack around with.

Drag and drop a file from the list into the vacant area underneath the AutoResponder tab and it will appear as a row with a checkbox to its left. As long as this is checked, Fiddler will hijack requests to this file and send out local versions of it rather than server versions.

Right-click on the file and select Edit Response. A pop-up appears; hit the TextView tab and you'll see the file's contents. Tweak it as you will, hit save, close the dialog (note: it will complain you have unsaved changes, even if you saved) and then refresh the browser.

You'll see your tweaks!

There's faaaaaaaaaaar more to Fiddler than that, as you can probably tell from the interface. But for a front-end developer, the above functionality alone has the potential to be a god-send. Enjoy.</description>
			<pubDate>2011-09-21 19:44:00</pubDate>
		</item>
	
	</channel>
</rss>

