Martin Ström
my-domain.se

Beforecast

Beforecast by Peter Ström and myself.


Quicker way to observe events in prototype.js

Here’s a shorter way to listen for events in prototype.js.


Copying to clipboard with JavaScript in Flash 10

As you might know, we have a feature on CopyPasteCharacter to let the user copy a character to their clipboard by just clicking on the character. An invisible Flash movie would do the copying using the ActionScript function System.setClipboard.

In October, Adobe updated the Flash Player to version 10, which included some security changes, like: “Setting the Clipboard will now have to be invoked through a button, keyboard shortcut, or some other event initiated by the user.”. This broke CopyPasteCharacter (and many other sites) for people running Flash 10. I had some ideas on how to solve workaround this a pretty long time ago but too little time to implement it until now.

We’re now having a fully working version which, since I couldn’t find any other solutions online, I thought could be useful for others/Google to know about.

The workaround I came up with is to use a hidden Flash movie which will get resized and moved to overlay the element/character where the user’s mouse is. This way, when the user clicks on the character, the Flash movie will receive the mouse event and therefore be allowed to set the system’s clipboard.

  1. The mouse roll overs a character.
  2. A JavaScript will resize and move the invisible Flash movie to match the character’s size and position
  3. The flash movie receives the mouseover and mouseouts so JavaScript can set the element’s class name (like a faked :hover selector)
  4. When (if?) the user clicks on the character, the click event will get received by the invisible Flash movie and not the document itself.
  5. The Flash movie asks JavaScript for the characters to copy (Clipboard#textToCopy) since it differs a bit depending on which element was clicked. Also, Flash tells JS if the the alt/option key was pressed (so the copy-multiple-characters-at-once feature works).
  6. The same #textToCopy function highlights the clicked element using the same code as we had for the Flash 9 version.

Here’s the code for the Flash movie (highlighted version)

import flash.external.*;

var text:String;

button.onRelease = function() {
  text = String(ExternalInterface.call("Clipboard.textToCopy", Key.isDown(KEY.ALT))) || ' ';
  System.setClipboard(text);
  trace('copied [' + text + ']');
}

button.onRollOver = function() {
  ExternalInterface.call('Clipboard.onFlashButtonOver');
}

button.onRollOut = function() {
  ExternalInterface.call('Clipboard.onFlashButtonOut');
}

The Clipboard class can be found here if you’re interested. It should keep the old behaviour for Flash 9 players but we had some problems with it in some browsers on Windows so right now all players get the updated code.

Note: This post has been lurking in my “Drafts” folder for about a month and shortly after we deployed the new code for Flash 10 a few weeks ago, I found the Zero Clipboard project which seems to use a similar approach as we did but as a stand alone library. I haven’t looked at the code yet but it seems promising.

Copy Paste Character

Two weeks ago we (me and Konst & Teknik) launched copypastecharacter.com—a site to make it dead easy to copy those special characters which otherwise can be hard to find. We just pushed an update and I realized I hadn’t mentioned it here.

The character you click will automatically get copied into your clipboard, thanks to the flash technique mentioned here. However, I wrote my own JavaScript class to handle the clipboard and the buffer of clicked characters since you can hold down ‹alt› to copy multiple characters at once.

Here’s the source for the copy buffer class in case anyone’s interested:


Multi-dimensional array sorter

The other day when working on some small updates on konst-teknik.se I wanted to sort the projects in a multi dimensional way, and take the other factors than the first into account. JavaScript’s Array#sort only supports one dimensional sorting so I wrapped my own sorter.

The results turned up pretty good (at least compared to the first test), or perhaps I just like recursing functions.



var sortOrder = {
  'cat-no': ['cat-no', 'name', 'type', 'year'],
  'name':   ['name',   'type', 'year', 'cat_no'],
  'year':   ['year',   'name', 'type', 'cat_no'],
  'type':   ['type',   'name', 'year', 'cat_no']
};

function sort(order) {
  var ordering = sortOrder[order], length = ordering.length;
  $$('#projects > li').sort(function(left, right) {
    left = Project.find(left), right = Project.find(right);
    return (function(index) {
      var a = left.getSortValue(ordering[index]),
          b = right.getSortValue(ordering[index]);
      return a < b ? -1 : a > b ? 1 :
        index < length ? arguments.callee(++index) : 0;
    })(0);
  }).each(function(project) {
    project.parentNode.appendChild(project);
  });
}


Ajax.CachedRequest

Recently I wanted to cache the results (responseText) from a lot of Ajax.Requests since the returning data would not change and made the roundtrip to the server unnecessary. Maybe there are others out there interested so here’s the code. It’s not very well tested except the project where it is in use so there might be some bugs or tweaks needed.


Ajax.CachedRequest = Class.create(Ajax.Request, {
  initialize: function($super, url, options) {
    options = options || {};
    var onSuccess = options.onSuccess || Prototype.K;
    if (!Ajax.CachedRequest.cache[url] || options.reload) {
      options.onSuccess = function(transport) {
        Ajax.CachedRequest.cache[url] = transport.responseText;
        onSuccess(transport);
      }
      $super(url, options);
    } else {
      eval(Ajax.CachedRequest.cache[url]);
      this.dispatch.defer();
      [onSuccess, options.onComplete].each(function(m) { m && m() });
    }
  },

  dispatch: function() {
    Ajax.Responders.dispatch('onComplete', null);
  }
});

Ajax.CachedRequest.cache = {};

Of course this assumes you’re using the brand new Prototype 1.6


Prototype & Script.aculo.us SVN checkins RSS feed

Thanks to Yahoo Pipes I created two RSS feeds for the Ruby on Rails checkins (changesets). One containing only the Rails-spinoffs checkins (that is Prototype and Script.aculo.us right now) and another without the spinoffs. This way I can follow the JavaScript-related changes as they happen but watch the Ruby-stuff every now and then.


What's new in Prototype svn?

Just after posting this I saw that sam tagged the 1.5.1 release in svn so I guess this means that 1.5.1 is final. Great work!

There has been a lot of action the past days in the Prototype SVN; the release of 1.5.1 RC4, the new DOM and Position branches and a lot of other work. Since I watch most of the tickets and changesets I thought I write something about what’s (might be) in the future for Prototype.

DOM branch

I was happy to see a patch I’ve been working on (#7476) to get included some days ago. It will define a new Element#writeAttribute method which will work together as the already existing #readAttribute to work around many issues browsers having with the native set/getAttribute methods (as always mostly in IE) but also to make chaining work:

$('my_image').writeAttribute('src', 'new-image.png').show();

The method will also accept a hash for the attributes to let you set multiple attributes at once:

$('my_image').writeAttribute({src: 'new-image.png', custom_attr: 'foo'}).show();

The patch will also make the Element object into a constructor for very easy and fast element creation (i.e. document.createElement wrapper):

var header = new Element('h1');

The constructor will also accept an optional attributes hash for the attributes (as seen above in the #writeAttribute method):

var header = new Element('h1', {id: 'myHeader'});

Of course chaining will work so for a simple image switcher with preloading you could do this:

<!-- html -->
<img src="thumbnail.jpg" id="thumbnail" hires="big.jpg">

// javascript
$('thumbnail').observe('click', function(event) {
    var thumb = Event.element(event),
      preloader = new Element('img', {src: thumb.readAttribute('hires')});
    preloader.observe('load', function(event) {
        thumb.writeAttribute('src', preloader.readAttribute('src'));
    });
});

Event Branch

I haven’t followed the event branch very closely but from the code and messages on the ML I’ve seen there should be new functionality for better garbage collection (to prevent memory leaks) and for e.g. easier removal of observers from elements.

Where you before had to manually collect all an element’s event listeners to be able to remove them later:

var listener1 = function(event) {...}.bindAsEventListener();
var listener2 = function(event) {...}.bindAsEventListener();

// start listening
$('myElement').observe('click', listener1);
$('myElement').observe('click', listener2);

// stop listening
$('myElement').stopObserving('click', listener1);
$('myElement').stopObserving('click', listener2);

you will now be able to remove all event listener for a specfic event:

$('myElement').stopObserving('click'); // or Event.stopObserving('myElement', 'click');

Other

Some other new additions worth mentioning are:

But to not make this post too long you’ll have to read about it on your own (check the source and/or the changesets manually).

Please notice that all these are subject to change since it’s under development right now and might never get into any future release of Prototype.


One animated background image for multiple elements in Safari

I’ve found out that Safari can’t handle the same animated gif as background for multiple elements, it will just animate one of them at the same time. On a project I’m currently working on my I use the following trick to make all requests to the background image (in this case indicator_black.gif) unique.

[...]
var text = transport.responseText;
if (Browser.WebKit) {
    text = text.gsub('indicator_black.gif', function(match) {
        return match + '?' + new Date().valueOf() +
          Math.round(Math.random() * 5000);
    });
}
[...]

Note that it uses Prototype JavaScript framework and you should too.

Update:

This is fixed in WebKit nightly (and therefore Safari 3 but I haven’t tested yet).

Rails' time extensions ported to JavaScript

I’ve ported Rails’ Numeric Time extensions to JavaScript since I needed to do some date calculations for a project I’m working on. Now one should be able to calculate dates in JS like this:

(5).seconds() // => 5000
(2).weeks() + (2).hours() + (15).seconds() // => 1216815000
(1).week().fromNow().toDate() // => Fri Sep 22 2006 19:16:32 GMT+0200 (CEST)
var date = new Date(2000, 11, 18, 18, 15, 23);
(2).years().since(date).toDate() // => Thu Dec 19 2002 06:15:23 GMT+0100 (CET)

Thought it could be useful for others as well. You’ll need the latest prototype library, unit tests are included.

Download a zip with both .js file and unit tests or just the .js-file.


TextMate Prototype & Scriptaculous Bundle

This the first version of a TextMate bundle for Prototype and script.aculo.us JavaScript libraries. The language grammar is based on from Justin Palmers Prototype Bundle but the other commands/snippets are all new. Please let me know if you have any comments and/or improvements.

Download here

Update 2006-07-16

The bundle is now added to TextMates official svn repository.

Prototypish Style Sheet Switcher

This is a Prototypish rewrite of Paul Sowdens Style Sheet Switcher. The original version has a lot of global functions so I put everything into a class instead and made the code a bit more elegant. It should work as the normal one except for some methods have been renamed.

A cookie library is included as well since the switcher needs to read and create cookies to save the users preferred style sheet.

Update

I fixed a bug for pages without any alternate style sheets and updated the script to version 0.2.

Download


WordPress theme

Finally this site looks like something other than the default WordPress theme. Peter and I wanted to connect our work sites to each other and decided to use his simple but easy-to-use WordPress theme as a base.

The problem was that his theme never was cross browser compatible and worked more or less only in Safari. My first task was to re-code the theme from scratch to make it work in all modern browsers using valid XHTML and CSS with as clean and simple code as possible.

I also set all font sizes using em:s (instead of px or pt) to make the text resizable. It wasn’t too hard making it work (even in Microsoft Internet Explorer) thanks to some great resources. Sooner or later I’ll convert the positions, margins etc to em:s as well, but font sizes should be enough for now.

I also added AJAX comments and used effects from script.aculo.us. I’m using Prototype to add CSS classes to some elements and to wrap i.e. all <h3>‘s content in a <span> to achieve the look I wanted without any unnecessary markup. Since <input type="search" /> only is supported by Safari and I wanted to use it, I used a script (thanks Wolfgang Bartelme) that replaces the regular text input field with a search field for Safari only. This way the document will stay valid XHTML 1.1.

Next task was to make the theme more personal for my site. I’ve tried some different looks but couldn’t really decide how I wanted it and choose (for now at least) a slightly darker version of Peter’s theme. I think it looks good and is easy to use without making too much noise.

When I implanted the tagging I first looked at Ultimate Tag Warrior 3 but it seemed too advanced for my needs, so I decided to use the native category system in WordPress 2.0, that lets one add tags (categories) by just entering them in separated by comma in a text field (WP 1.x didn’t have this feature). The tag cloud is a modified and simplified version of Tag Cloud Plugin.

Download

Update April 20, 2006 The theme is now released in a beta version. Some notes: * You’ll need the [Post Updated Plugin](http://guff.szub.net/2005/02/22/post-updated) to get a page’s last modified date. * My “lite” version of the [TagCloud plugin][tagcloud] can be [downloaded here][tagcloudlite]. * You’ll problably want to change the `autosave` attributes value in `javascripts/global.js` (line #24) to your own unique id. [Read more on the attribute](http://weblogs.mozillazine.org/hyatt/archives/2004_07.html#005890). I also found this great plugin for the admin area, [Cat2Tag](http://www.agkamai.org/cat2tag) The link seems to be broken, get it download it here for now for easier tagging of your content without using a separete database like [Ultimate Tag Warrior 3][utw] does. Cat2Tag just use WordPress’ own categories instead. [Download](http://my-domain.se/wordpress/wp-content/uploads/burnfield-dark.zip).
Update May 4, 2006 The [TagCloud plugin][tagcloudlite] is updated to use the [rel-tag](http://microformats.org/wiki/rel-tag) [microformat](http://microformats.org/about).
Update August 18, 2007 Since a lot of people ask me how to get the thumbnails to work, here is the instructions I usually email them:

— ✄ ——————

First, download a newer version of `posts-thumbnail.php` replace the current one (from the downloaded .zip file) with this one attached in this message. Create the thumbnail image and name it “thumb-POST_SLUG.png”. The post slug is shown on the “edit post” screen in the admin (i.e my latest post with title “Rails’ time extensions ported to JavaScript” has post slug “rails-time-extensions-ported-to-javascript” and the thumbnail should therefore be named “thumb-rails-time-extensions-ported-to-javascript.png”). Then just upload the image from the same screen using WordPress’ built-in uploader (you dont have to give it any description or title). Then the theme should automatically find the image for you and show it in the list view.

———— ✄ ——

Btw is a new version of this theme under development and will make the thumbnail handling easier.
Update October 31, 2007 The link to the plugin “Cat2Tag” seems to be down (thanks Kris Aubuchon) so, for now at least, you can download it here. I haven’t really looked into the new tagging system in WP 2.3 so perhaps this plugin isn’t necessary any more.

Pluxemburg

pluxemburg-site.png

Pluxemburg is a record label I’m co-running with some friends. The site in its current form is almost two years old, but a lot of things have changed since it was first released. Since I just released some updates, I thought I’d write something about them and show how the CMS/administrative interface works.

Recent site updates

I won’t go through the whole site and tell you everything about it. Instead, go browse it by yourself. The shop has been improved with a smarter cart that doesn’t forget your items if you by accident reload your browser or hit the back button. Validation is more clear and better looking in the same style as the improved (and AJAX powered) guestbook and newsletter subscription.

Browser support

When the site launched almost two years ago, it fully supported Internet Explorer 5 (Mac), IE 5, 5.5 and 6 on PC and of course, old and new Firefox versions, Mozilla, Safari etc etc. It was a pain to fix the CSS especially for IE Mac and IE5, IE5.5 on Windows. Currently, I’ve dropped support for MacIE (it’is not even supported by Microsoft any more), IE5 and IE5.5 for Windows. I think the site should work more or less using outdated browsers, but it might not look exacly as intended.

CMS and site admin

The site is powered by an advanced CMS that helps us adding and editing news, products in the shop, guestbook spam and a lot of other things. When I first wrote it for this site, I had in mind to keep it so general I could, so it could be extended and used in other projects. Of course the administrative interface is password protected, but I’ve recorded two movies showing some parts of it. I’ll convert the movies to H.264 right after this is posted, so for now, the movies are pretty large in size. The movies are now in H.264 format and are 75% smaller (before: total 44.8 MB, now: 11.6 MB)

The first movie, shows a basic task such as adding some news items to specific part of the site and then view it. Pretty basic.

Watch the first movie (QuickTime 7, 20.9 3.1 MB)

The second show how easy it is to manage products in the shop, as well as track orders.

Watch the second movie (QuickTime 7, 23.9 8.5 MB)

To download them, hold the ⌥ (alt) key down and click the link or right click and choose “Download Linked File”

You’ll need QuickTime 7 to watch them.


Marie Frans

Website and CMS for swedish photographer’s agency I made together with Peter. We also did their graphic identity.

The frontend is optimized to be a fast, simple but effective way of browsing the photographers and their photos, check it out. The CMS makes it easy for the photographers to upload, edit and organize their photos and for the site editors to write news and edit information on the site. It’s a customized version of the administrative interface I coded for pluxemburg.com with added functionality such as image uploading and photo organization. I wanted to let the server handle the image resizing and creation of thumbnails as well, but found out that PHP’s image functions didn’t do as good work as expected. I tried all kind of different techniques but we ended up using Photoshop and manually make the thumbnails. Photoshop does a way better job and with this kind of client (working with photographs) we wanted as good quality as possible.

I’ve made a movie (QuickTime, 4.9 MB) showing how the admin interface works when uploading and reordering the photos, since it’s password protected. You’ll need QuickTime 7 to watch it.

Update 2006-03-13

Since the agency and the site was shut down some weeks ago, I’ve put up some screen shots to show how it was done. I might record a movie and/or a mirrored version for reference.

Index

mf-index.png

Photographers

mf-photographers.png

Photos

mf-photos.png

Loading a photo

mf-loading.png

Showing a photo

mf-show.png

Information

mf-info.png


Konst & Teknik site

Konst & Teknik website

My friends over at Konst & Teknik asked me to code their web site. It’s only one page, that should show the results from Google Image searches for the word in their name, “konst” and “teknik” (“art” and “technology” in swedish). I liked the idea and also got the opportunity to do some ruby scripting and try the Prototype JavaScript library.

Server side

Since Google currently doesn’t offer any API to do other searches than pure web searches and we wanted to use Google Image Search, I had to do my own image fetching script. The script is a ruby script that will pull the images and info from Google Images and store them in a local index file. First, I used Net::HTTP but I found out that it had problem dealing with the swedish characters (used in swedish, ie åäö) so I changed the URL-fetching to use curl instead, witch also was slightly faster. The index is written from ruby using Marshal. It is scheduled to run twice a week using cron.

Client side

My first approach was to make one class that downloads and shows the image for the given keyword. Then create one instance for each word (konst and teknik), controlling the preloading and image-switching every 4th second (meaning; updating one of the images every second second). But I found out it was hard to make the updates smooth and exacly on time.

Instead I split the client side script into of two main classes, the Preloader class and the Switcher class. The Preloader triggers a request using AJAX to a server side ruby script that will return a new random image from the image index and then stores the info received from the server in a local array. After some delay the script will start over again with a new request for another image. When the Preloader is done indexing some images then the Switcher will kick in and start showing them and switch every other second between the images for each word as long as there are images preloaded and ready to be shown. If the Preloader is out of preloaded images then the Switcher will pause and show a loader while the Preloader’s buffering. We wanted the images to be vertical aligned by bottom but I couldn’t make it work with CSS only (nor with vertical-align, float or position). Instead, the script is switching between two <div>s (for each word, totally four divs) and when the “not active” div got a new image loaded into it, it will find its dimensions and set its margins automatically. The next time it’s time to switch image (for this word) this div will be shown instead, the other one becomes invisible and get the next image loaded.

The script should work fine in Safari, Firefox, Camino etc (even WinIE6). It needs some code cleaning (mostly OO-issues; currently I’m referencing the instances from the class, which I think is a bit ugly) but I’m releasing it anyway.

Check it out http://www.konst-teknik.se


Fast del.icio.us-poster bookmarklet

I took Hitchhiker’s Sogudi shortcut and modified it to use a JavaScript-prompt() to ask for the tags. Use it in Safari as the first bookmark or so and activate it by pressing ⌘+1 (or other number depend on where on the bookmark bar it is)

Installation:

  1. Drag this link to your Bookmark bar: + del.icio.us
  2. Right click on the bookmark and choose “Edit Address
  3. Change CHANGEME to your del.icio.us username
  4. Done

CSS is in progress