technicalpickles

Open Source ProjectsCode that Might be Useful to You

Talks I've GivenOn Technologies and Ideas

ThoughtsWhere I Sometimes Write Things

Resume If You Believe In Those

Follow Me On

GitHubIf coding is your thing

TwitterIf you tweet

Focusing a form field at page load with MochiKit


As far as I can tell, the only way to make a form field be focused by default at page load is by using Javascript.

Code snippets you find online will typically do something like:

<html>
  <head>
    ...
  </head>
  <body onload="document.someform.somefield.focus()">
    ...
  </body>
</html>

That’s nice and all, but this can be problematic when you have other onload methods for your body tag.

MochiKit has some nice facilities for handling events like this, what it calls MochiKit.Signal. It allows you to connect however many functions to a particular event as you need.

Here’s how I did it:

<html>
  <head>
    ...
    <script type="text/javascript" src="/your/path/to/MochiKit.js"></script>
    <script type="text/javascript">
      var focusInitialInput = function() {
        document.someform.somefield.focus();
      }
      connect(window, 'onload', focusInitialInput);
    </script>
  </head>
  <body>
    ...
  </body>
</html>

Pretty simple. This is only scratching the surface of MochiKit’s Signal handling.

comments powered by Disqus