MooTools 1.2 Beginners Guide Book Review

MooTools 1.2 Beginners Guide from Packt Publishing
After a year of using jQuery, I have an upcoming project that requires me to go back to MooTools. A lot of my MooTools knowledge was rather rusty, but a couple of weeks ago the nice people at Packt published a new book called MooTools 1.2 Beginner’s Guide and I managed to get my hands on a copy.

MooTools 1.2 Beginner’s Guide by Jacob Gube and Garrick Cheung promises readers they will “learn how to create dynamic, interactive, and responsive cross-browser web application using one of the most popular JavaScript frameworks”, and it certainly does that.

The book is very clearly written, with plenty of step by step examples. You’ll need a basic understanding of HTML, CSS and JavaScript but not much more.

The book starts out explaining what MooTools is, how to go about downloading it and then using it on a web page. It clearly explains the difference in using normal JavaScript code and MooTools code, before moving on to DOM selectors and other key utilities in the MooTools library. In addition to this, there are chapters on events, AJAX, animations and plugins.

When the book arrived I expected a very simple book, and I have to admit to having been pleasantly surprised. As well as being an excellent tutorial for beginners, there is actually quite a lot for the more experienced developer and I found myself picking up quite a few new tricks, and clarifying my knowledge in a few places. One area that MooTools has always been weak in comparison to rival frameworks like jQuery has been the quality of the documentation and tutorials for beginners, this book really addresses that area and should be a welcome addition to the library of any MooTools developer.

MooTools 1.2 Beginners Guide Official Website.

Maintaining The Scroll Position On An ASP.NET Page After Postback

I had a requirement today for an ASP.NET page to jump to the same part of the page once a form was submitted via a postback.

Qudos to my fellow developer Andy Howell for leaping in and pointing out that functionality was already in ASP.NET 2.0 and above, so there would be no need for me to write any funky JavaScript.

You need to set MaintainScrollPositionOnPostback to true. I did this in the Page tag on the ASP.NET page.

<%@ Page MaintainScrollPositionOnPostback="true" %>

Although I’ve not tested it yet, you should also be able to set it globally in the web.config file in the pages section.

<pages maintainScrollPositionOnPostBack="true" />

Or programmatically in the code behind.

System.Web.UI.Page.MaintainScrollPositionOnPostBack = true;

For more information on this, see the MSDN page for System.Web.UI.Page.MaintainScrollPositionOnPostBack.

Double Dash In HTML Comments

While working on FHM.com earlier today I came across an odd bug on a page. On Firefox 3, parts of the page were rendering incorrectly, while on Internet Explorer everything was fine.

Browsers rendering content differently isn’t anything new, but most of this site is derived from common templates, and only a small part of the page was directly inserting HTML. This was the obvious place to look.

Looking at the source code with syntax highlighting turned on revealed the problem, and it was one i’d not come across before.

The site had a comment that included two dashes next to each other, something like this

<-- A test comment -- test -->

Looks OK doesn’t it? Well it’s not valid XHTML, hence the problem.

XHTML is based on XML so follows it’s standards. Here is the standard for XML comments.

The key wording here is, the string ” — ” (double-hyphen) MUST NOT occur within comments.

The same applies to HTML, have a look at what the HTML4 spec says about comments. This is down to HTML being based on SGML, and double dashes are SGML comments.

In the end, it’s Firefox obeying the spec, and other browsers not. However, things look like they are due to change.

Due to these problems, SGML comments have been removed from Acid 2, and future HTML versions will not require SGML comments. Browsers that have implemented them are now expected to remove their support for SGML comments, for all HTML versions.

Read more about HTML and SGML comments.

Fixing A Jumping Audio Stream In ActionScript 3

We’re changing the format our streaming radio feeds at the moment and our test player kept jumping. We were a bit stumped as to what could be going on as the same code runs our current listen again functionality.

Delving into the ActionScript 3 code, we discovered that it appears to be down to how we implemented the NetStream object that handles the live stream. There is a variation between a live publishing stream and an archive subscribing stream and how they work with the buffer.

On a subscribing stream, the bufferTime attribute specifies how long to buffer incoming data before starting to display the stream. However, on a publishing stream, bufferTime specifies how long the outgoing buffer can grow before the application starts dropping frames.

We had our bufferTime set too low, the default is 0.1. We have now upped this and our problems have gone.

See the Adobe reference site for more information on the ActionScript 3 NetStream bufferTime attribute.

Creating A New Element With jQuery, With Or Without A Plugin

UPDATE: Whilst this remains an interesting example of creating a simple plugin, I no longer recommend this way of creating elements in jQuery. Instead just pass the html you want to use into jQuery directly as a string, e.g. var myH1Element = jQuery("<h1>My H1 Test</h1>");.

One function that seems to be missing in jQuery is to create new elements outside of the current DOM.

There is a good reason for this, normal vanilla JavaScript has the function createElement to do the job for you.

To create a new h1 element for example, we can do the following.

var myH1Element = document.createElement('h1');

We can easily combine this with jQuery to set the text inside for example…

jQuery(myH1Element).text("My H1 Text");

There is one downside, using the standard createElement we’re not able to chain functions with jQuery.

The way around this is to wrap the request in jQuery like this…

jQuery(document.createElement("h1"));

Now we can chain this together as before…

jQuery(document.createElement("h1")).text("My H1 Text");

If you don’t like the look of that, then we could always create a jQuery plugin, and add a createElement function to jQuery.

jQuery.extend({
createElement : function(elementName) {
return jQuery(document.createElement(elementName));
}
});

That must be one of the simpliest jQuery plugins ever!

Now we have extended jQuery with a createElement function we can chain calls to it like this.

jQuery.createElement("h1").text("My H1 Text").appendTo("body");

This will create a new h1 element, add the text “My H1 Text” inside the h1, then append the h1 inside the documents body tag.

Using A Canonical URL

Websites that can be accessed from multiple URL’s aren’t very search engine friendly.

Sometimes this structure may have evolved by accident as a site was developed at different times on varying technologies. You don’t want to turn off the old links as that would loose valuable search engine equity, but you don’t want them scattered on multiple URL’s either.

There is a solution, and that is to use a canonical URL.

The easiest is to add a simple link element to the page with it’s correct canonical URL. For example, if we have a page that can be reached at www.example.com/test.html, example.com/test.html or beta.example.com/test.html. we only want this to be index at www.example.com/test.html, so we can use add a link element as follows…

<link rel="canonical" href="http://www.example.com/test.html" />

Notice the use of rel="canonical", this is tells a search engine if it has accessed the page from another URL, it’s actually meant to be indexed from this URL.

Google, Yahoo and Microsoft have all agreed to support this canonical link element.

Another approach is to redirect the user to the page on the correct URL server side. Using Apache, this can be done using a RewriteRule and couple of RewriteCond‘s.

Using the same example, the rewrite rule would be something like this

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www.example.com [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/(.*) http://www.example.com/$1 [L,R=301]

Here we make sure we’re not already accessing using the correct domain name. If we aren’t, the we redirect using the L flag to make sure this it’s the last rule run, and R=301 to issue a 301 Moved Permenantly redirect. Anyone visiting the page on an incorrect domain, will now be redirected to the right page.

Using jQuery And Mootools On The Same Page

While it’s never a good idea to bloat your webpage with too much unneeded content, there are times when you can’t avoid it. One example I came across recently was with my day job’s adoption of jQuery as our official JavaScript framework, I needed to add some jQuery goodness to some blog pages belonging to a certain category in Movable Type. Simple, right?

Well the site in question already used Mootools extensively, so the jQuery would have to run nicely next Mootools and not disrupt existing functionality.

The designers of jQuery have designed for this sort of situation, and have provided a function called noConflict that returns the use of $ to Mootools, or any other framework you may have installed as well.

Here’s some example code to show both jQuery and Mootools running in the same page…

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

In my Movable Type situation, I am able to use a custom MT tag to make sure jQuery only appears for certain categories. Let’s assume I have a category called jQuery where I need the jQuery library to be imported, the MTIfCategory tag is what I need to guard with…

<MTIfCategory label="jQuery">
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript"><!--
jQuery.noConflict();
//-->
</script>
</MTIfCategory>
<script type="text/javascript" src="mootools-1.2-core-yc.js"></script>

With this in place I can call jQuery functions using the jQuery variable, and MooTools using $ where necessary.

Using Config Files In Catalyst

I’ve been doing quite a bit of work with the Catalyst MVC framework lately.

Moving from development to live, the config system has really shown it’s usefulness. Instead of hardcoding values, we can simply move them out to the site’s config file and access these value programatically. It means we can run the same codebase on multiple machines and just tweak the config to pick up things like different database connection strings, cache settings etc.

I like to have my config file in Config::General format as it’s similar to Apache’s config files, but Catalyst can also handle config files in INI, JSON, Perl, XML or YAML, so you can use whatever you are most comfortable with.

Let’s have a look at a few examples. We’ll assume the Catalyst Application is called MyApp. This means we’ll have a perl module in our lib directory called MyApp.pm, and a config file called myapp.conf in the root directory.

MyApp.pm contains all the default values, but you can override these with myapp.conf. myapp.conf always takes priority.

Let’s create a simple string to say where our application is running. In MyApp.pm, in the __PACKAGE__->config we add an entry to the hash like this…


servername => 'dev',

Now when we run our application, we can access this value using the following code…


$c->config->{servername};

This will return “dev”. We can override this in the conf file, so in myapp.conf we can add…


servername production

Now when we run our application code, we’ll see “production” instead of “dev”.

A more practical use of the config file is to move out the database connection details. Let’s assume we have a simple MySQL based model in our lib/Model directory called Model::MyApp that handles our database work. We can override database connection details stored here in myapp.conf using something like this…

<"Model::MyApp">
connect_info dbi:mysql:myapp
connect_info www-rw
connect_info password
<connect_info>
AutoCommit 1
</connect_info>
</"Model::MyApp">

Now when we run the application, the connection details we entered in our conf file will be used instead. This is very useful as it means we don’t have to alter our codebase when we move the application to different servers that may have different databases. It’s also good for keeping dev, staging and live seperate as all that’s needed is a change to one config file.

For more information on how Catalyst can use a config file, have a look at
Catalyst::Plugin::ConfigLoader.

Alternating Table Rows With JavaScript And jQuery

One of the most popular stories on this website is on Alternating Table Rows With Template Toolkit And CSS. The example I use is how to stripe alternate rows in an HTML table by applying a seperate class to each row.

As I’ve been learning jQuery lately, I thought I’d update this example to show how to do it using this excellent JavaScript framework.

Firstly, we need to setup our styles. We’ll have a lite and a dark class to use that will just set a different background colour.

<style type="text/css">
.lite {background-color: #ddffff;}
.dark {background-color: #aaffff;}
</style>

We’ll also need an example table.

<table class="stripe">
<tbody>
<tr>
<td>1</td><td>One</td>
</tr>
<tr>
<td>2</td><td>Two</td>
</tr>
<tr>
<td>3</td><td>Three</td>
</tr>
<tr>
<td>4</td><td>Four</td>
</tr>
<tr>
<td>5</td><td>Five</td>
</tr>
</tbody>
</table>

Notice how I have given the table a class of stripe. This is important, I’m going to use jQuery to only select table elements that have this class name, else every table on the page would be striped.

The jQuery to achieve the striping is actually very simple.

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('table.stripe>tbody>tr:even').addClass("lite");
$('table.stripe>tbody>tr:odd').addClass("dark");
});
</script>

Firstly we added the jQuery library to the page. Next we setup our striping code to only run once the DOM is place. This is important as we’re going to be selecting and manipulating over the DOM next. The next two lines apply the lite class to even table rows and the dark class to odd table rows. Let’s look at this in a bit more detail.

The selector $('table.stripe>tbody>tr:even') is easier to explain backwards. We look for even matching tr elements, that have a parent of tbody, that has a parent of table with a class of stripe. The use of the > symbol instead of just a space is to make sure the elements are direct parent and child elements instead of just ancestor and descendant. Why is this important? Well if we used a space any nested tables that happened to have an striped ancestor would also be striped. This isn’t normally what we’d want to happen.