10.27.06

Posted in JavaScript at 11:48 pm by jasonb

I have found jscalendar to be an effective, if bloated, solution for integrating a DHTML calendar into an existing form input field requiring a user to enter a date and optionally a time. However, for it transparently effective, it needs to appear when a user brings focus to the form field and disappear when focus is lost. While you can configure jscalendar to respond to an onFocus event for the inputField and to close on single click outside its window, you cannot presently prevent an onFocus event from creating multiple instances of the same calendar as you provide and remove focus from your input field. Fortunately, I have resolved that today.

First, allowing jscalendar to appear when an onFocus event is triggered is provided for by default. In a Rails helper somewhere I included the code below with eventName defined to onFocus.

calendar = <<-EOF
  Calendar.setup({
 inputField : "#{id}",
 ifFormat : "%Y-%m-%d",
 singleClick : true,
 eventName : "'focus"
  });
EOF

That’s only half the problem, though. Second, by including the Prototype JavaScript framework, the Event#bind method can be used to listen for an onBlur event. To allow for the calendar to be hidden when focus is lost on an inputField bound to jscalendar, the code below must be included in calendar-setup.js.

if (mustCreate) {
      cal.create();
      // Prototype bind magic so we don't get multiple
      // calendars open from onFocus firing on each
      // date field.
      Event.observe(
      params.button || params.displayArea || params.inputField,
      'blur',
      function(ev) {
        this.hide();
     }.bind(cal))
}

jscalendar can now be displayed when a field gains focus and disappear when it loses focus, allowing for someone to tab through fields without lingering or overlapping calendars. Enjoy the magic!

It’s useful to note that this presents a calendar that cannot be clicked on to effect under Konqueror 3.3.2 and 3.5.2. I don’t know about Sarfari, which is KHTML based, as I don’t have access to OSX. In IE6 jscalendar seems to grab focus, so it isn’t possible to accidently create multiple calendars by tabbing through with onFocus set.

Leave a Comment

Stop spam with the thorough-paced, above par, and strong Wordpress Spam-be-gone plugin.