Most read posts this month



Sep 21st 2009 × jsPrintSetup: an AMAZING plugin for firefox that gives extended javascript controls to the printer

This is not a tool you can rely on for customer-facing development, but I found it invaluable nevertheless. jsPrintSetup is a small fireFox add-on that hands you a controlling object in javascript. You get FULL access to any print-related function you could think of: list printers, select default printers, print silently, control spool, headers… There’s just too much to mention. Very useful when coding a CMS that needs to print specific things to specific printers (for example, invoices on printer #1 and labels on printer #2).

Here is an example that fetches a list of printers and remembers the user’s preference for future use:

// only do something if the plugin is live
if ($type(jsPrintSetup)) {
    var printers = jsPrintSetup.getPrintersList().split(","); // get a list of installed printers

    // no print dialogue boxes needed
    jsPrintSetup.setSilentPrint(true);

    // create a dropdown
    var printList = new Element("select", {
        id: "printerList",
        events: {
            change: function() {
                Cookie.write("defaultPrinter", this.get("value"), {
                    path: "/admin/",
                    duration: 365
                });

                // save the new printer selection
                jsPrintSetup.setPrinter(this.get("value"));
            }
        }
    }).injectTop($("printSetup"));

    // get default by preference if any
    var defaultPrinter = Cookie.read("defaultPrinter");

    printers.each(function(el) {
        new Element("option", {
            value: el,
            text: el,
            selected: (defaultPrinter == el) ? "selected" : false
        }).inject(printList);

    });

    // attach an event that prints from an element called goPrint
    $("goPrint").addEvents({
        click: function() {
            jsPrintSetup.print();
        }
    });
}

Sep 15th 2009 × mootools colour picker: mooRainbow

I was browsing around the internet and came across Iconza by turbomilk. As it seemed rather nice and my Framework Detector Firefox add-on sniffed out mootools, I had a look at the source.

It uses what looks like a colour picker plugin for mootools called mooRainbow. Nice to have in your toolkit, you never know. Iconza’s png trickery is not too shabby either, nice site (as you’d expect from Turnomilk anyway).


Aug 4th 2009 × Stop bot spam without OCR: hOOmanTest – a modern javascript captcha class

It has always annoyed me as a user when having to strain my eyesight and having to type weird letters or numbers in order to prove I am a human. The practice is known as ‘captcha’ and dates back a while now. Regretfully, nothing much has changed aside from the ability of the bots to OCR better – we still need to read some obtuse characters.

This is why I wrote a javascript mootools captcha class called hOOmanTest – making the whole ‘prove you are not a bot’ a lot easier to stomach. Regretfully, it has no degradation as it relies on drag and drop, but you can use reCaptcha inside your target div as the fallback and have the class apply an .empty() before populating it, providing the upper layer.

*edit*: I really do hope it helps somebody, here is the first site that uses it out there–in a quotation webform on the cleaning 4u site, click the free quote banner to view.


Aug 3rd 2009 × Enough of the jQuery already…

This is not much of a post but a bit of a rant. “It’s my party and I’ll cry if I want to”, right?

I have a problem with jQuery–not with the framework as such, but with some of its users. And who in their right mind wouldn’t be getting the amp when just about any webdev site, forum and topic is now full of clever know-it-alls that come and declare how ‘such and such jQuery plugin will do what you want’. There’s always a jQuery plugin for everything, didn’t you know…

Does not matter if the question at hand is on vanilla javascript or mootools, just add jQuery and whistle… Already use another framework? Get jQuery anyway, it’s so good you can run in compatibility mode!

The sad part is in how a large portion of these jquerysts have absolutely no understanding of vanilla javascript. It feels as if some of them inadvertently consider ‘javascript’ and ‘jQuery’ to be synonymous…

Aren”t people just getting carried away slightly? I’ll be the first to admit how jQuery is full of awesome features, documentation and support. Why, it’s so great and so far removed from standard javascript syntax that some go to extreme lengths to mimic its shorthand in other frameworks as well. Just the other, having downvoted a jQuery solution for a mootools question on stackoverflow, I was told how $(“someid”).click(); was a perfectly reasonable and valid mootools syntax (as shown by David Walsh)

Paradoxically, in lowering the standards and requirements (in the sense of, by being too accessible and too easy to use), jQuery has spawned an army of coders that don’t even have to learn javascript. A lot of badly formed code gets released, complete with a disregard for best practices, memory, bandwith use, usability and god knows what else…

Still, perhaps there will come a day when mootools sports a high-spirited in-your-face following. For we have a lot to be tooting about, after all…


Jun 22nd 2009 × facebOOkTips: mootools facebook style tooltips – update

I have had the facebook tooltip available as a part of my core library for a while now. However, usage on various sites highlighted certain visual errors in the way it rendered on sites with custom CSS settings for line-height and line-spacing. This (plus the ineffectiveness of the old way the tooltip arrow was injected) caused me to sit down and refactor the whole function. Look at the demo tooltip page for possible uses.


Jun 20th 2009 × mootools 1.2.3 released, bug fixes and compatibility with other frameworks

Nathan White announced the mootools 1.2.3 release today. This is to be the last version prior to bumping everything into mootools 2.0.

Although mootools 1.2.3 is mostly about bug fixing, it does introduce an important feature: “Element: MooTools compatibility mode: the $ function is only defined if no pre-existing $ function is found. If an existing $ function is found, you can use document.id()”

In reality this means that mootools will be able to co-exist with frameworks such as jQuery (or others). It will still not work alongside Prototype, for example – extending prototypes just cannot be namespaced. Also, even though you now CAN use more than one framework at a time, you probably shouldn’t do so on the same page, its a wasteful and needless practice.


Jun 12th 2009 × imageScrOOler: a mootools image thumbnails scrolling class with carousel effect

*update* 15/09/2009 – Added a new option, carousel: true|false, which creates a never-ending wrap of the image set. Check the imageScrOOler example page for more.

I have had this in my pipeline a while now but it’s time to release it for whoever needs this kind of thing. The idea is simple: have an array of images that are scrolling from left to right and right to left in a containing layer with a possible click event that goes to a relevant URL.

Here is an example using some brands and a click through to their respective pages (taken from webtogs.co.uk where the original script for 1.11 resides):

imageScrOOler example

The code used to generate this

// compose your data through PHP or whatever:
var mc, sdata = [{image: '4.jpg', url: '/Berghaus/', title: 'Berghaus'},
{image: '88.jpg', url: '/Big_Agnes/', title: 'Big Agnes'},
{image: '63.jpg', url: '/Brasher/', title: 'Brasher'},
{image: '35.jpg', url: '/Bridgedale/', title: 'Bridgedale'},
{image: '65.jpg', url: '/Buff/', title: 'Buff'},
{image: '3.jpg', url: '/Camelbak/', title: 'Camelbak'},
{image: '6.jpg', url: '/Craghoppers/', title: 'Craghoppers'},
{image: '93.jpg', url: '/Crumpler/', title: 'Crumpler'},
{image: '39.jpg', url: '/Deuter/', title: 'Deuter'},
{image: '86.jpg', url: '/Haglofs/', title: 'Haglofs'},
{image: '71.jpg', url: '/Helly_Hansen/', title: 'Helly Hansen'},
{image: '95.jpg', url: '/Icebreaker/', title: 'Icebreaker'},
{image: '92.jpg', url: '/Inov8/', title: 'Inov8'},
{image: '61.jpg', url: '/Jetboil/', title: 'Jetboil'},
{image: '31.jpg', url: '/Keen/', title: 'Keen'},
{image: '97.jpg', url: '/Kuhl/', title: 'Kuhl'},
{image: '48.jpg', url: '/Trangia/', title: 'Trangia'},
{image: '42.jpg', url: '/Vango/', title: 'Vango'},
{image: '44.jpg', url: '/Vaude/', title: 'Vaude'},
{image: '52.jpg', url: '/Victorinox/', title: 'Victorinox'}];

window.addEvents({
    domready: function() {
        mc = new ImageScrOOler(sdata, {
            imagePath: "http://www.webtogs.co.uk/brands75/",
            imageHeight: 85,
            targetElement: $("scr"),
            clickEvent: function(obj) {
                window.location.href = "http://www.webtogs.co.uk" + escape(obj.url);
                // can use a lightbox or whatever instead - for example, if your obj has a property .largerImage,
                // you can modal / largerBox it instead of a direct url visit.
            },
            showProgress: false,
        });

        // it also supports events in case you want to do something once scroll ends...
        mc.addEvent("complete", function(direction) {
            console.log("hello from events, we just finished moving all the way to the " + direction);
        });
    },
    beforeunload: function() {
        mc.stop();
        mc.options.targetElement.empty();
    } // end domready
});

All you need to do is include your mootools more and moootools core, then imageScr00ler.js. Change as you deem fit, use as you like – any linkback or such can’t hurt. Just have a look at the source code and the possible methods and uses on the imageScrOOler example page and use your common sense. I hope somebody does find it useful, any feedback / ideas is always appreciated.


Jun 8th 2009 × jquery vs mootools: a look at what each framework represents and how to choose wisely

Aaron Newton has written up what appears to be one of the most comprehensive and unbiased answers to the eternal question: jquery or mootools. I cannot recommend it enough to anyone that’s just starting with javascript or is looking at both frameworks from the “which is better for me and my project’s needs” angle. It’s worth mentioning before you begin, this is a comparison of the core functionality, provided by each framework – not what is possible should you decide to build on it.

The short summary: both frameworks are great but serve a different purpose, with jquery is more user and beginner-friendly, focused / optimised around DOM access and mootools, building and extending the javascript native prototypes and methods (not at the expense of the things that jquery can do).

Another way to look at it: mootools takes things further than jquery and makes javascript fun, introduces features that are coming in javascript 1.8 and provides a great layer for object orientated programming whereas jquery is staying where it’s at its best: shortcuts, chaining and styling, leaving anything else you may need to plugins and vanilla javascript.

http://jqueryvsmootools.com/

The comments are also well worth the read, some good points on the pro’s and con’s of each framework and a bit on why mootools does not try to be unobtrusive / conflict free with other frameworks.


Apr 30th 2009 × javascript obscure exception trapping and reporting via AJAX for mootools

I’ve had this post in my submission bin for a while but a question of the digital point forums today prompted me to dig it out… First of all, what is the difference between a javascript exception and a javascript error? Well, my view on this is simplistic: an exception IS an error of a runtime nature that can be handled, whereas an error is typically to do with syntax and can’t be ‘caught’.

So why would we care of exception errors anyway?
Whilst programmers take every possible measure to release compliant and bug-free code for all possible browsers, the sad truth is that–for ajax-rich applications–no amount of testing can ensure things won’t break for somebody. There always will be the ‘daft’ people, their quirky old browsers (IE6, anyone?), odd plug-ins, proxies / anti-virus software, leap years and so forth–somehow managing to trigger unexpected javascript exceptions. The more traffic you get, the better the chances are for somebody to stumble upon such difficulties. What you don’t always get is people phoning up to tell you about it. Not unless it’s something critical – like the inability to add an item to a shopping basket or failure to checkout. And let me tell you, your customer services won’t be able to get any meaningful debug information.

A practical example?
Recently I got a report of a customer that was unable to checkout and for whom the ‘checkout’ button did nothing. The button itself had an onclick event assigned to it within the mooTools domready function… Surprisingly, it turned out the domready just consistently fired up earlier than expected for him, with the checkout.gif image just not being a part of the DOM at the time of the event assignment. This got me worried and made me want to try and discover other such potential deterrents to people’s browsing experience.

The solution is closer when you know your problem areas…
I created a javascript exception trapping handler and placed it around what was perceived to be the ‘dangerous / unsafe’ portions of the checkout code. The handler itself was set to use XHR (ajax) to send me the exception data via email, alongside of whatever additional data the PHP script was able to grab (browser, user info, basket contents and so forth). The results were… astonishing. This quirk was happening a fair bit more than we would have liked (1 in 30 customers). We also found out that our promo codes buttons were also being affected… The flaw in the mooTools 1.11 domready code aside, how did we fix it? By not assigning events until all the elements were available, by using load as opposed to domready for IE users and so forth.

Here is the refactored code for mootools 1.2+ instead:

var errorHandler = function(dbug) {
    // trap errors and send via ajax to a script that logs them
    new Request({
        url: "/errorTrap.php",
        data: dbug,
        onComplete: function() {
             $("errorOutput").set("html", this.response.text);
        } // comment this function out out and the comma on the line above. data will arrive via $_POST.
    }).send();
    return true;
}; // end errorHandler

$("makeException").addEvent("click", function(e) {
    new Event(e).stop();
    try {
        duffColours[2] = 0;
    } catch(er) {
        errorHandler(er); // install it.
    }
});

And here is an example of the errorTrap.php contents, I’d advise you to do data washing/escaping as well:

<?PHP
$body = "ERROR DETAILS FOLLOW:\n\n";

foreach($_REQUEST as $key => $value) {
    $body .= "$key: " . str_replace('"', '\"', $value) . "\n";
}

$body .= "\n----------------------------------------------------\nServer variables:\n\n";
foreach($_SERVER as $key => $value) {
    $body .= "$key: " . mysql_escape_string($value) . "\n";
}

mail("your@email.com", "JS exception on {$_SERVER['HTTP_REFERER']}", $body);
?>

To create an exception, click here – it will send it to a file called errorTrap.php, which iterates the $_GET and $_SERVER variables before dispatching me the email

Error output here


Apr 24th 2009 × mootools 1.2.2 released

Just a quick update, in case you missed it: mootools 1.2.2 is out, mostly a bug fixing release. Also, the new mootools-more is out. So… check them out.