Freelancing Gods 2015

15 Oct 2007

A Quick Focus on Javascript

Neat little refactoring trick for the day (as I’ve just recounted to the roro crew)…

I found myself writing several window.onload event listeners in javascript to set focus to the default text inputs on various pages. It’s annoying, and doesn’t feel at all elegant, so to make it a little cleaner, I wrote a single onload listener, which grabbed the last item with the class ‘autofocus’, and set focus to that. So now all I need to do for future pages is give the text input a class of ‘autofocus’.

Javascript code, with prototype:

Event.observe(window, "load", function() {
  var last = $$(".autofocus").last();
  if (last) last.focus();

Not so useful if you rarely have default text fields, but for the app I’m working on, there’s a lot of different pages, hence why I’m quite happy with the above solution.


3 responses to this article

15 Oct 2007
Anthony kolber said:

You should try out jquery meng.
The $() function is lovely. Faster than prototype and feels much more elegant.

15 Oct 2007
Pat said:

Yeah, would like to really get stuck into jQuery, but at the moment I’m using the Autocompleter from scriptaculous, and a lightbox built off prototype…

If I get bored, I might try rewriting those parts into jQuery, but unlikely that’ll happen anytime soon.

17 Oct 2007
Ben Schwarz said:

You should probably apply that code to an event model like “domready” rather than onload, as that encompasses images and external scripts being available to the DOM.

Having said that, I believe that pure HTML can give you more advantage rather than using Javascript here.

You may want to use another attribute (other than class) that has more semantic meaning

Leave a Comment

Comments are formatted using Textile. Please be respectful of others when posting comments. Be nice.

RssSubscribe to the RSS feed

Related Links

Related Posts

About Freelancing Gods

Freelancing Gods is written by , who works on the web as a web developer in Melbourne, Australia, specialising in Ruby on Rails.

In case you're wondering what the likely content here will be about (besides code), keep in mind that Pat is passionate about the internet, music, politics, comedy, bringing people together, and making a difference. And pancakes.

His ego isn't as bad as you may think. Honest.

Here's more than you ever wanted to know.

Open Source Projects

Other Sites

Creative Commons Logo All original content on this site is available through a Creative Commons by-nc-sa licence.