1. 01. Incoming
  2. 02. Hifi
  3. 03. Lofi
  4. 04. The Lab
  5. 05. Tags

frequency decoder

Unobtrusive Date-Picker Widget V4

Posted Tuesday February 03, 2009

frequency decoder

A complete rewrite of the previous datePicker script that throws much asked for features into the mix

To all & sundry: I’ve finally managed to devote some time to a complete rewrite of the datePicker/calendar script – again. Full details on the latest version can be found on the Unobtrusive Date-Picker Widget V5 article page.

The LowDown

My 3rd and final attempt writing a datePicker (calendar) that is accessible using the keyboard, requires no embedded JavaScript blocks, uses no pop-up windows and is suitable for use within documents served as application/xhtml+xml.

The more impatient amongst you may want to see the various demos before reading any further.

At a glance…

  • Fully keyboard accessible
  • Multiple date formats and date dividers supported
  • Unobtrusive and nameSpace friendly
  • Fully skinnable with CSS
  • Both upper and lower date limits can be set
  • Certain days of the week can be disabled
  • Certain dates can be disabled/enabled (and wildcards used to stipulate the dates in question)
  • Includes “smart” localisation
  • Bespoke days of the week can be highlighted
  • Works with single text inputs, split text inputs or select lists
  • It’s free to use, even commercially (Released under a CC share-alike license)

New features include…

  • Numerous accessibility enhancements including support for ARIA Roles and States
  • All keyboard shortcuts now adhere to The DHTML Style Guide Working Group (DSGWG) recommendations
  • DOM friendly – the calendar is only added to the DOM when actually required
  • DatePickers can now display an optional status bar and week numbers
  • DatePickers can now be dragged around the screen (activated by clicking on either the datePicker’s header or footer)
  • Lower and upper date limits can now be set using either a YYYYMMDD date String or a relative “days”, “weeks”, “months” or “years” notation
  • The script can parse and format dates using a subset of the PHP strftime conversion specifiers
  • Global configuration parameters can now be specified using JSON within the script tag itself
  • The “button” used for popup datePickers can now be styled for default, hover, active and disabled states, be arbitrarily positioned within the DOM and removed from the document tabindex if so desired
  • Inline datePickers are now available (i.e. no button activation is required), are automatically added to the document’s tabIndex and can be arbirarily positioned within the DOM
  • A bespoke final opacity can be defined for pop-up datePickers and the fade in/out animation effect disabled
  • The entire grid can now be filled with dates
  • Bespoke “append id’s” can now be set for datePickers split over 3 form elements
  • The “Today” button can be removed from the U.I.
  • Three bespoke events, “dateselect”, “redraw”, and “create” are now available

f.a.q

Here’s a quick list of frequently asked questions you may also wish to ponder before reading any further:

Can the calendar show multiple months?
No, this was never imagined at the beginning of the project and would require a substantial rewrite to achieve – I may try to work on this feature if I ever manage to grab some free time.
Can users also select a time?
I’m afraid not. The datePicker only allows the selection of dates, not datetimes.
The calendar looks huge on my site w.t.f?
Your page is rendering in quirksmode which means that TD’s inherit a font-size that is 80% of the default browser font size (normally 16px). You need to tweak the CSS file to set a smaller font-size on the TDs.
I need a dual license
Ask and ye shall receive… The script is released under a creative commons Attribution-ShareAlike 2.5 license but if you require something more specific I’ll be happy to comply.
Can you help me with X/Y/Z?
Most probably not. I prefer to spend time with my kids. I hope that doesn’t sound too uppity or condescending but it would be a full-time job in itself to help out everyone who asks.
Is there a forum?
I’m afraid not, try asking your question politely in the comments.
Hey asshat, you deleted my comment!
Sorry about that, please don’t take it personally but it probably didn’t add anything to the conversation or was a question that had previously been answered. The last datepicker article garnered over 400 comments which added a network footprint of about 500k to the page in question; I’m just trying to keep things on-topic and relevant this time around. No hard feelings (I’ve not actually deleted any comments as of yet but I’ll leave this info just in case).
Can you select multiple dates using one datePicker?
Again, I’m afraid not. The calendar was designed to enable users to quickly select one single date, not a date range. It’s possible by using two datePickers and a little scripting – I’ll create a little demo that shows how to do it as soon as I possibly can.

Creating datePickers

Each datePicker has to be associated with either one single text input or three distinct form elements (any combination of text inputs or select lists).

There are two methods available to create datePickers; the first passes all configuration parameters by setting classes on the associated form element’s className, while the second uses a JavaScript call to create the datePicker (the last datePicker on the demo page has been created using JavaScript and not by adding classNames to the associated form element).

For example, to create a basic “popup” datePicker that uses a dd/mm/yyyy date format, the following HTML would suffice (don’t be put-off by the dateformat class, it’s really quite easy to compile and is explained in more detail below) :

 
<input type="text" id="anID" name="dt" class="dateformat-d-sl-m-sl-Y" value="" />
 
 

To create an inline datePicker (i.e. one that is always displayed on screen) that uses an identical dd/mm/yyyy date format, we just add another class “display-inline”:

 
<!-- The class "display-inline" creates an inline (non-popup) datePicker -->
<input type="text" id="anID" name="dt" class="dateformat-d-sl-m-sl-Y display-inline" value="" />
 
 

Another example, this time creating a popup datePicker split across 3 text inputs:

 
<!-- Year part: We add all of our classes to this form element -->
<input type="text" id="anID" name="dty" class="split-date" value="" />
<!-- Month & Day parts, located automatically by the script 
     as their id's have been given the appendages "-dd" and "-mm" -->
<input type="text" id="anID-mm" name="dtm" value="" />
<input type="text" id="anID-dd" name="dtd" value="" />
 
 

All of the configuration classes are described in detail below.

Popup datePickers

By default, the script creates “popup” datePickers i.e. an activation button is positioned beside the associated form element and the datePicker only appears when the button has been activated (by using either the mouse or keyboard).

The activation button (actually an HTML link styled to look like a button – which keeps it in the document’s tabindex) is, by default, positioned directly after the associated form element within the DOM.

The bespoke positioning of the popup datePickers’ activation button

Should you wish to position a the activation button within a bespoke DOM node, just give the associated form element the class button-XXX where the XXX represents the ID of the DOM node that you wish to position the button within. For example, adding the class “button-myDiv” will tell the script to add the datePicker’s activation button as a child of the DOM node with and ID of “myDiv”.

Removing the button from the document tabindex

This can be done by using the “buttontabindex” property within the JSON passed to the script – this is explained in more detail within the section Setting Global configuration parameters.

Inline (non-popup) datePickers

If you wish to have the datePicker always displayed on screen i.e. with no activation button; just add the class display-inline to the associated form element’s className. By default, the script adds inline datePickers to the DOM as the next sibling of the associated form element.

The bespoke positioning of inline datePickers

Should you wish to position inline datePickers within a bespoke DOM node, just give the datePicker’s associated form element the class display-inline-XXX where the XXX represents the ID of the DOM node that you wish to position the datePicker within. For example, adding the class “display-inline-myDiv” will tell the script to add the datePicker as a child of the DOM node with and ID of “myDiv”.

Splitting the date across three form elements

The datePicker can work with dates that have been split across a combination of text inputs or select lists i.e. three unique form elements; one for the day part, one for the month part and one for the year part. Just add the class split-date to the className of the associated form element representing the year part. It stands to reason that datePickers split across three form elements in this way do not have to set a date format.

In order for the script to be able to locate both the associated month and day form elements, the form element representing the month should be given the same ID as the form element used for the year but with the String “-mm” added to the end and the day form element should again be given the same ID as the form element used for the year with the String “-dd” added to the end. All of the other configuration classes should be added to the year form element’s className only.

Using bespoke “append id’s”

Should you wish to change the default append id’s of “-dd” and “-mm”, the new appendages can be passed using JSON within the script tag – this is explained in more detail within the section Setting Global configuration parameters.

Select lists and automatic date ranges

As a select list can only ever stipulate a finite range, the datePicker will automatically create a higher and lower date limit using the select list data i.e. if the year select list starts at 1960 and ends at 1990, the associated datePicker will automatically disallow the selection of dates outside of this range.

Select lists and invalid dates

Should the user select an invalid date e.g. 31st September (remember, September has only 30 days), the datePicker will automatically correct the date to be the 30th September.

Date formats

DatePickers that have not been split across three distinct form elements require that you define a date format. This is achieved by adding the class dateformat-XXX to the associated form element’s className where XXX represents a list of conversion specifiers taken from the following table:

Specifier Description
d Day of the month, 2 digits with leading zeros (01 – 31)
j Day of the month without leading zeros (1 – 31)
D An abbreviated textual representation of a day (Mon – Sun)
l A full textual representation of the day of the week (Monday – Sunday)
N ISO-8601 numeric representation of the day of the week 1 (for Monday) through 7 (for Sunday)
w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
S English ordinal suffix for the day of the month: st, nd, rd or th
z The day of the year (starting from 0): 0 – 365
W ISO-8601 week number of year, weeks starting on Monday: 1 – 53
M A short textual representation of a month, three letters
F A full textual representation of a month, such as January or March
m Numeric representation of a month, with leading zeros
n Numeric representation of a month, without leading zeros
t Number of days in the given month: 28 through 31
Y A full numeric representation of a year, 4 digits
o ISO-8601 year number. This has the same value as Y
y A two digit representation of a year
sp A whitespace character
dt A full-stop: “.”
sl A forward slash: “/”
ds A minus/dash: “-”
cc A comma: “,”

For example, to give a datePicker a dd/mm/yyyy date format e.g. 13/03/1970, just add the class “dateformat-d-sl-m-sl-Y” to the associated form element’s className.

Date parsing

The script now has a much more forgiving approach to parsing dates and no longer forces you to rigidly enter dates in the format specified within the “dateformat” class.

The script will first check to see the associated input element’s value matches the format supplied within the “dateformat” class; if not, it attempts to match the input value against the following list of common date formats:

  • yyyy/mm/dd
  • mm/dd/yyyy
  • dd/mm/yyyy
  • yyyy-mm-dd
  • mm-dd-yyyy
  • dd-mm-yyyy
  • dd-mm-yy
  • dd/mm/yy

The list of alternative date formats used by the script when parsing dates can be changed to suit your installation by passing JSON within the script tag – this is explained in more detail within the section Setting Global configuration parameters.

Displaying a status bar

To show a status bar, just give the associated form element a class of the form statusformat-XXX where XXX represents the same list of conversion specifiers defined with the section Date formats.

Highlighting days of the week

By default, Saturday and Sunday are highlighted in another colour (in a burgundy red for the demo). Should you wish other days of the week to be highlighted instead, add a class of the format highlight-days-N to the associated form element’s className where N represents is a numeric representation of the days you wish to highlight e.g. adding the class “highlight-days-012” will highlight Monday (0), Tuesday (1) and Wednesday (2).

Localisation

The script attempts to auto-detect the primary language of the user’s browser installation and download the corresponding language file from the server. Should the language file not exist, the datePicker display defaults to English.

Should your browser’s language have a region code set (i.e. en-US), the script will also attempt to download the language file associated with this region code.

The following language files are currently available:

  • American English
  • Brazilian Portuguese (thanks to “g0dkar”)
  • Catalan (thanks to Thomas Sjödin Dahl)
  • Czech (thanks to Stano Matousek)
  • Danish (thanks to Brian Jensen)
  • Dutch (thanks to Alfred Vorsselman)
  • French
  • German (thanks to “too many people to list”)
  • Indonesian (thanks to Krishna Hendrakusuma)
  • Italian (thanks to Valerio Pilo)
  • Korean (thanks to Taehyun Kim)
  • Latvian (thanks to Māris Kiseļovs)
  • Norwegian (thanks to Geir Rune Brandt)
  • Portuguese (thanks to Paulo Monteiro)
  • Russian (thanks to Кирилл Асташов)
  • Spanish (thanks to Augusto)
  • Swedish (thanks to Henrik Marik)
  • Turkish (thanks to Ogan Keskiner)

Many thanks to the above contributers for their time and effort in creating the localisations.

If you don’t see your language in the list, you can easily create one by using the language file creator script. I would, of course, appreciate a copy of the new file to add to the distribution – thanks!

Stipulating a language to use

You can disable the detect locale functionality and stipulate the required language by using JSON within the script tag – this is explained in more detail within the section Setting Global configuration parameters.

Alternatively, you can simply reference the desired language.js file before the datepicker.js file as is shown below:

 
<!-- Add the American English "en-us.js" file -->
<script type="text/javascript" src="/the/path/to/en-us.js"></script>
<!-- Now add the datepicker.js file -->
<script type="text/javascript" src="/the/path/to/datepicker.js"></script>
 
 

Please note, in order for the script to successfully download language files, they should be placed within a directory named “lang”, itself resident within the same directory as the datepicker.js file.

The locale used when formatting dates that include non-numeric date parts

Should no language be explicitly defined for use as described above (i.e. the auto-detect functionality has kicked in and downloaded a language file from the server), the date displayed within the status bar and TD nodes will display using the downloaded locale but all dates formatted for updating the associated input’s value will display in English.

This is to make life easier on the server, as you know for certain that English (and not Spanish or French for example) dates are being returned for processing e.g. the English version “Friday, 13 March 1970” will be returned and not the French “Vendredi, 13 Mars 1970”.

Should a language be explicitly defined, the date returned to the server will always use this language.

The “first day of the week”

The first day of the week is currently stipulated within the downloaded language file. Should the language file not contain this setting, the first day of the week defaults to Monday.

Additionally, users can click on any of the day headers to dynamically set it as the first day of the week (or alternately, press the numbers 2-7 on the regular keyboard or numpad whenever the datePicker is keyboard accessible).

Limiting date selection

The datePicker enables you to define both a lower and upper limit for date selection.

To add a lower or upper limit, stipulate them as part of the associated form element’s className by using either the range-low-XXX or range-high-XXX classes, where XXX represents a YYYYMMDD date String; for example, adding “range-low-20051202 range-high-20061220” to the className will limit the selection of dates to between the 2nd, December 2005 and the 20th, December 2006.

Using a relative date notation

Additionally, the lower and upper limits can be set using a “days”, “weeks”, “months” or “years” relative notation, for example, adding “range-low-1-year range-high-6-weeks” to the className will set the lower limit to be one year before the current date and the upper limit to be six weeks after the current date.

Defaulting date limits to the current date

Should you just wish to default either the upper or lower limits to today’s date, you can add either of the classes range-high-today or range-low-today.

Setting the date range dynamically

The upper and lower date ranges can also be set programmatically by calling the following two methods:

    
/* NOTE: all occurences of "myElementID" should be replaced with the ID of the associated form element */
// Set the lower limit to be 01/12/2008
datePickerController.setRangeLow("myElementID","20081201");
// Set the upper limit to be 01/12/2009
datePickerController.setRangeHigh("myElementID","20091201");
    
  

Be warned, the script does no validation checks on the date ranges when altered in this way so it’s up to you to validate the date ranges before calling the methods in question.

Disabling day selection

You can now stipulate days of the week to disable. This is done by adding the class disable-days-N to the associated input’s className, where N is a String of integers representing the days of the week you wish to disable; for example, adding the class “disable-days-12” will disable Monday (1) and Tuesday (2) for the associated datePicker.

Disabling date selection

You can stipulate dates to disable by adding a className of the form disable-XXX where XXX represents a date String of the form YYYYMMDD; for example, adding the class “disable-20091225” will disable the 25th December 2009.

If multiple dates are to be disabled, just repeat the className multiple times; for example, adding the classNames “disable-20090313” and “disable-20090314” will disable the 13th and the 14th of March 2009.

Stipulating wildcards within the disabled date

Wildcards can be used when stipulating the dates to disable by substituting the day, month or year parts with the wildcard character “x”; for example, adding the className “disable-xxxx1225” will disable the 25th of December for all years, adding the className “disable-xxxxxx25” will disable the 25th of every month for every year.

Disabling a range of dates

Entire ranges of dates can be disabled by using a className of the form disable-XXX-XXX” where agaihn, the XXX represents a date String of the form YYYYMMDD; for example, the class “disable-20090301-20093101” will disable all dates between the 01st and the 31st of March 2009. No wildcards should be used when disabling ranges in this way.

Disabling date selection programmatically

Dates can be programmatically disabled by calling the setDisabledDates or addDisabledDates methods of the datePickerController Object.

Both methods accept an Array of YYYYMMDD format date Strings (that may themselves include wildcards); for example passing the Array ["20091225", "****1231", "******01"] to the setDisabledDates method will disable the 25th of December 2009 (“20091225”), the 31st of December for all years (”****1231”) and the first day of every month for all years (”******01”).

  
// Disable multiple dates by passing an Array 
datePickerController.setDisabledDates("the associated input id", ["20061225", "****1231", "******01"]);
// Disable a single date (you don't need to pass an Array 
// if this is the case)
datePickerController.setDisabledDates("the associated input id", "20061225"); 
  
  

The setDisabledDates method will delete the current list of disabled dates before adding the new ones while the addDisabledDates method will add the dates to the list of dates already present.

Please note that the wildcard character used is an “x” when passing dates within the className and an “*” (asterisk) when calling either of the setDisabledDates or addDisabledDates methods.

Disabling the fade in/out animation effect

To disable the fade-in/fade-out effect, just add the class no-animation to the associated input’s className.

Setting a bespoke opacity

To set a bespoke opacity for popup datePickers, just add the class opacity-XX to the associated form elements’s className where XX represents an Integer value between 10 and 99.

Showing week numbers

To display week numbers, just add the class show-weeks to the associated form elements’s className.

Removing the “Today” button from the U.I.

To remove the button, just add the class no-today-button to the associated form elements’s className.

Setting the default cursor date

By default, the cursor date is set to today’s date but there may be times when you wish the cursor to start at a date of your choice (when stipulating a range of valid dates, you may wish for the cursor to start at the beginning of the range for example).

This is achieved by adding the class cursor-X to the associated form element’s className where X represents a date in the YYYYMMDD format. For example, to start the cursor at December 25th 2009, you would add the class “cursor-20091225” to the associated form element.

Hiding the associated form elements(s)

To hide the associated form element(s), just add the class hide-input to the associated form element’s className. This will tell the script to hide the form element(s) by setting their display property to “none”, which means their value is still sent to the server when the form is submitted.

Disabling the drag effect

To disable the drag effect for an individual datePicker, just add the class disable-drag to the associated form elements’s className.

Disabling the drag effect for all datePickers

Disabling the drag effect for all datePickers can be achieved by calling the datePickerController.setGlobalVars method or using JSON within the script tag – this is explained in more detail within the section Setting Global configuration parameters.

Filling the entire grid with dates

Should you wish to fill the entire grid with dates just add the class fill-grid to the associated form element’s className. By default, dates not falling within the current month are selectable, should you wish to stop the selection of these dates, use the class fill-grid-no-select instead.

Styling the datePicker

The datePicker currently ships with a rather basic CSS skin as, for simplicities sake, I purposely tried to style the entire thing using only one CSS file i.e. using no CSS files targetted specifically for Internet Explorer by using conditional comments.

The CSS file is well commented so altering the colours etc to suit your installation should be a relatively easy task.

Styling individual dates

To enable you to target and style individual dates using CSS, each TD node is now given two extra classNames of the format yyyymm-YYYYMM and mmdd-MMDD, where MM is replaced by the two figure month value and YYYY replaced by the four figure year value e.g. the TD node for the date 21/03/2007 will be given the classNames “yyyymm-200703” and “mmdd-0321”.

Setting Global configuration parameters

The script now accepts the passing of Global configuration parameters by using a JSON Object within the script tag – an example of this is shown below:

   
  <!-- Notice how the JSON Object is passed within the script tag -->
  <script type="text/javascript" src="/the/path/to/datepicker.js">
  {
  "nodrag":1,
  "lang":"en",
  "formats":["Y-ds-m-ds-d","m-ds-d-ds-Y","d-ds-m-ds-Y"],
  "split":["-day","-month"],
  "buttontabindex":true,
  "cellformat":["Y-ds-m-ds-d"],
  "titleformat":["Y-ds-m-ds-d"]
  }  
  </script>  
  
 

It’s worth noting that JSON notation doesn’t care about whitespace so the above code block could have been written in one line (with no line breaks).

Should the Douglas Crockford JSON parser exist within the global namespace, it is used to parse the JSON passed to the script.

Additionally, you can programmatically pass the JSON Object by calling the datePickerController.setGlobalVars method as is shown below:

    
<!-- Load the datePicker script -->
<script type="text/javascript" src="/the/path/to/datepicker.js"></script>
<!-- Now create our JSON Object and pass it to the "setGlobalVars" method -->
<script type="text/javascript">
// Create the JSON Object
var myJSON = {
  // disable the drag & drop for all datePickers
  "nodrag":1,  
  // Set a list of formats used to parse theuser entered date
  "formats":["Y-ds-m-ds-d","m-ds-d-ds-Y","d-ds-m-ds-Y"],
  // set the "append id's" used to locate split date form elements
  "split":["-day","-month"]
};
// Pass it to the script immediately - this should be done 
// before the window's onload event fires
datePickerController.setGlobalVars(myJSON);  
</script>  
  
 

It is also worth noting that only the variables you wish to set need to be defined within the JSON Object; for example, should you only wish to disable the drag effect for all datePickers, you would use a JSON Object of the form:

    
  {
    "nodrag":1    
  } 
  
 

The following parameters can be passed to the script using JSON:

“nodrag”
Accepts the Integer value “1” and disables the drag effect for all datePickers.
“lang”
Accepts a two letter iso639a language code and attempts to retrieve the corresponding language file from the server. This variable is only taken into consideration when passing the JSON between the script tags and has no effect if passed to the setGlobalVars method.
“formats”
Accepts an Array of date format Strings that are used when attempting to parse a user entered date.
“split”
Accepts an Array containing two Strings representing the “append id’s” required by the script when locating the “day” and “month” part form elements (for split date datePickers).
“cellformat”
Accepts a date format String that is used to create the full date for each TD cell whenever the the associated datePicker has keyboard control. This parameter defaults to the value “d-sp-F-sp-Y” i.e. “13 March 1970”. Only the date format parts “d” or “j” are visibly displayed, the rest is hidden from view but made available to screen-readers.
“titleformat”
Accepts a date format String that is used to create the title attribute for each TD cell. This parameter defaults to a screen-reader friendly value of “F-sp-d-cc-sp-Y” i.e. “March 13, 1970”
“buttontabindex”
Accepts a Boolean value that adds or removes all popup datePicker activation buttons from the document tabIndex (Note: Removing the buttons from the document tabIndex means that the associated datePicker cannot be controlled using the keyboard).

The active “cursor”

An active cursor is necessary as the datePicker is keyboard accessible and keyboard users require a visual clue as to which date is currently active i.e. which date will be selected when the carriage return key is pressed.

The default sylesheet shows the selected date with a black border and black text and the current cursour position in blue.

Accessibility

The datePicker now includes features theoretically designed with assitive technologies in mind.

I say theoretically as, not being a seasoned screen reader user myself, the testing has been nominal in this regard and until I manage to get some feedback from actual screen reader users, I can’t actually say for sure that the accessibility additions help or hinder the intended audience.

The table structure

The HTML table representing the datePicker has been marked up with a THEAD, TBODY and, if a status bar is used, a TFOOT.

The TH nodes representing the day names have their scope attribute set to “col” and the nodes representing the week numbers, if used,
have their scope attribute set to “row”.

A text file that lists the HTML used to create an example datePicker is available for those of you wishing to see the entire table structure – including classes, ARIA roles and states and hidden screen-reader text within the TD nodes etc.

The use of the TITLE attribute

Each focusable TD node has been given a title attribute that uses a default format of “F-sp-d-cc-sp-Y” to describe the cell’s representative full date, for example, “March 13, 1970”.

As some screen reader users disactivate the reading of title attributes, I also add the full date to each TD node but display only the day part of the date. All other date parts are hidden within span nodes that are positioned off-screen.

This means that screen reader users will still have a full date read aloud whenever the active “cursor” is given focus by the script.

By default, the TD cell date format is of the form “d-sp-F-sp-Y” i.e “13 March 1970” but both this and the title format can be changed to suit your needs by passing JSON within the script tag – this is explained in more detail within the section Setting Global configuration parameters.

Keyboard accessibility

All keyboard shortcuts now adhere to The DHTML Style Guide Working Group (DSGWG) recommendations.

Keeping the keyboard or mouse button depressed activates a timed increment i.e. there’s no need to repeatedly press the mouse button or arrow keys.

Pressing Enter selects the currently highlighted date, pressing Esc closes the datePicker without selecting a date and Space highlights todays date. Additionally, pressing 2 to 7 (using the numpad or regular keyboard) now sets the associated day to be the “first day of the week”.

The datePicker can be controlled using the keyboard in the following scenarios:

Inline datePickers

Inline datePickers are automatically placed into the document’s tab order – which means that they can “have focus”.

Once focused (i.e. the user has tabbed to the datePicker control), they can be controlled using the keyboard.

Popup datePickers

Should the datePickers associated “button” be activated using the keyboard (i.e. by focusing on the button and then pressing Enter), once launched, the datePicker will be able to be controlled using the keyboard.

Should the button be activated by a mouse click, the datePicker will launch without active keyboard control.

ARIA Properties & Roles

The following ARIA Roles have been set for the datePicker:

ARIA Roles
Role Associated HTML element
grid Assigned to the TABLE
gridcell Assigned to all TD nodes
row Assigned to all TR nodes within the TBODY
columnheader Assigned to all of the TH nodes representing the day of the week
rowheader Assigned to all of the week number TH nodes (if present)
button Assigned to a popup datepicker’s activation button

The following ARIA Properties have been set for the datePicker:

ARIA Properties
Property Associated HTML element
hidden Assigned to the wrapper DIV for all invisible popup datePickers, the first two TR nodes within the THEAD (used to display the day & month and navigation buttons) and disabled datePickers and activation buttons.
selected Assigned to the currently selected date’s TD node
describedby If the HTML page has an element with an ID of “fd-dp-aria-describedby”, then this is used to set the describedby relationship
labelledby If the associated form element has a label, the label is used to set the “labelledby” relationship
haspopup Assigned to a popup datepicker’s activation button
disabled Assigned to a disabled datePicker

Problems & Questions regarding the script’s accessibility

Unfortunately, the Opera web-browser adds a non-customisable “focus” outline to each TD node which encapsulates the hidden span elements within the TD. This makes the focus outline in Opera stretch beyond the left hand side of the viewport and actually hinders accessibility for people with low vision.

To stop this happening, I currently don’t add the hidden text in Opera. If anyone can show me a better, non-problematic method for hiding the text (whilst still making it available to screen readers) that does not incur the wrath of the Opera focus outline I’d be happy to hear it.

Testing in FireVox (A Screen Reading extension for FireFox) quickly revealed that the on-demand creation of popup datePickers was causing a problem (at least for FireVox users) as every new DOM node dynamically added to the screen was being read aloud. To combat this, I’ve attempted to hide the datePicker from screen readers during the creation by using a combination of display:none and visibility:hidden.

Additionally, creating and adding the hidden spans is a processor intensive action which makes the U.I. sluggish in poor old Internet Explorer.

Callback functions

There are currently three callback functions available for the datePicker; “dateselect”, “redraw”, and “create”.

All callback functions are also stipulated by setting classes on the associated form element’s className.

For example, to stipulate a callback function named someCallback for the “create” event, you would add the following className to the form element: cb_create_someCallback.

As can be seen, the className should be of the form cb_X_Y, where X represents the callback you wish to use and Y the function to call.

Using Object.methods as callback functions

Object.methods can be stipulated by converting the “dots” (i.e. the full-stops) to minus signs (-); for example, the className “cb_create_myObject-myMethod” will tell the script to call the “myMethod” method of the JavaScript Object “myObject” e.g. myObject.myMethod(); whenever the “create” callback event fires.

Callback function arguments

All callback functions are passed a Javascript Object containing information on the status of the datePicker itself – these are detailed below:

 
// The "dateselect" callback function receives the following...
{ 
"id": the ID of the associated form element, 
"date": a Javascript Date Object representing the selected date,
"dd": the date part of the selected date, 
"mm": the month part of the selected date, 
"yyyy": the year part of the selected date
}
// The "create" callback function receives the following...
{ 
"id": the ID of the associated form element
}
// The "redraw" callback function receives the following... 
{
"id": the ID of the associated form element, 
"dd": the date part of the current cursor date, 
"mm": the month part of the current cursor date,
"yyyy": the year part of the current cursor date, "firstDateDisplayed": the first date currently shown by the calendar (yyyymmdd format), 
"lastDateDisplayed": the last date currently shown by the calendar (yyyymmdd format)
}
 
 

Additionally, the “redraw” callback can return a Javascript Object that stipulates classNames to add to specific dates. For example, the following Object, when returned from the “redraw” callback function, will add the class “santa” to the TD that represents Christmas day 2009:

  
{
20091225:"santa"
}
  
  

As can be seen, all dates should be stipulated in a YYYYMMDD format within the returned Object.

The Javascript A.P.I

The datePickerController Object has a slew of public methods. These are described below:

Method Description
addEvent(obj, type, fn) A classic addEvent function (just in case you need one)
removeEvent(obj, type, fn) A classic removeEvent function
show(inputID) Makes a popUp datePicker associated with a form element having an ID of “inpID” appear (fade in)
hide(inputID) Makes a popUp datePicker associated with a form element having an ID of “inpID” dissappear (fade out)
destroyDatePicker(inpID) Removes the datePicker associated with the form element having an ID of “inpID” from the DOM (and browser memory)
cleanUp() Loops through the current list of in-memory datePickers and checks to see if their associated form element exists within the DOM; if not, the datePicker is itself removed from the DOM (and browser memory).
repositionDatePickers() Repositions popUp datePickers to align to their associated activation button. Usefull if the screen size is changed.
printFormattedDate(dt, fmt, useImportedLocale) Accepts three arguments, a Javascript Date Object, a date format String and a Boolean value (that instructs the script to use the imported locale or default to using the English locale). Returns a String.
setDateFromInput(inpID) Instructs the datePicker to update it’s currently selected date by parsing the associated form element’s value. Usefull should you use Javascript to change the value of the form element in question.
setRangeLow(inpID, yyyymmdd) Accepts two arguments, a String representing the associated form element ID and a second String representing a YYYYMMDD date.
setRangeHigh(inpID, yyyymmdd) Accepts two arguments, a String representing the associated form element ID and a second String representing a YYYYMMDD date.
parseDateString(str, format) Accepts two arguments, the first a fully formed date String (e.g. “13th March 1970”) and the second, a date format String that the first argument is parsed against. Returns a Javascript Date Object on success or FALSE on failure.
setGlobalVars(JSON) Explained in more detail within the section Setting Global configuration parameters.
dateValidForSelection(inpID, date) Accepts two arguments, a String representing the associated form element ID and a Javascript Date Object. Returns a Boolean value indicating whether the date is valid for selection or not i.e. within the date ranges and not disabled etc
setDisabledDates(inpID, dts) Accepts two arguments, a String representing the associated form element ID and an array of “YYYYMMDD” date Strings to disable. Calling this function will reset all currently disabled dates for the datePicker. Wildcards are accepted within the date Strings.
addDisabledDates(inpID, dts) Accepts two arguments, a String representing the associated form element ID and an array of “YYYYMMDD” date Strings to disable. Calling this method will add the dates to the list of currently disabled dates. Wildcards are accepted within the date Strings.
disable(inpID) Adds the class “fd_disabled” to the datePicker (and, if necessary, the datePicker’s activation button) and stops all mouse and keyboard interaction with the datePicker.
enable(inpID) Removes the class “fd_disabled” from the datePicker (and, if necessary, the datePicker’s activation button) and reenables all mouse and keyboard interaction.
createDatePicker(options) Creates a datePicker using the options Object passed in as an argument. An example of using this method can be seen by looking at the demo source code.

For example, to use the cleanUp method, you would use the following Javascript:

 
datePickerController.cleanUp();
 
 

Bugs and foibles

The inevitable list of known cross-browser foibles:

Internet Explorer

Our good friend Internet Explorer requires (for reasons that I won’t detail here) that each form element associated with a datePicker has a unique ID attribute assigned to it.

As mentioned previously, the new accessibility enhancements make the U.I. sluggish in Internet Explorer, whose Javascript engine isn’t as fast as other A-Grade browsers.

Chrome

Chrome has issues with the “-webkit” styles used to round the corners and add a drop shadow. The only available “fix” is to remove the styles from the stylesheet and wait for the Chrome team to add better, non-buggy support for the selectors in question. Fixed in 2.0.172.33.

Opera

Opera is an ass and has problems styling TD nodes that have a CSS opacity set (in fact, it styles the first node correctly but does not set the opacity on any sibling nodes).

Opera also tends to never collapse the space left after a datePicker is initially created and then hidden – even if display:none and visibility:hidden are used. This means the demo page has a rather large gap of whitespace at the end of the page.

Additionally, Opera point-blank refuses to update the status bar text. I’ve tried every hack/fix I could think of (including but not limited to: removing the old node and creating a new one with the updated text, cloning the old node and adding the updated clone, using a wrapper span around the text, setting an obscene marginLeft on the node, updating the text and then resetting the marginLeft, setting the node’s display property to none, updating the text and then resetting the display property etc) but to no avail.

Should the status bar be scrolled out of the viewport and then scrolled back into view, the updated text magically appears… what finesse!

The License

The script is now released under a creative commons Attribution-ShareAlike 2.5 license. Should you use the script within a commercial context (or are feeling generous today), please think about clicking the payPal donate button – it’s certainly not an obligation but it would most certainly put a smile on my face.

Demo, downloads and updates

View the updated date-picker demos or download an 90k .zip of the necessary files (HTML, CSS and Images).

The .zip download currently includes two (entirely untested) compressed versions of the script; the first version was compressed using Dean Edwards Packer and the second using the YUI compressor.

Note: I’ve only tested this version with lowly IE6 & 7, FireFox3.5, Safari 3 & 4b (win), Chrome 2.0.172.33 and Opera 9.64.

09/07/2009 (v4.5):

  • Made enabled dates take precedence over disabled dates and disables days of the week
  • Added the “cursor-X” functionality that enables you to set a default cursor start date
  • Added code to enable language regions to be taken into account when attempting to download the required language file
  • Added more language files to the download
  • Added a “createDatePicker” method to the controller to enable you to create datePickers using JavaScript

03/04/2009 (v4.4):

  • Fixed a bug in the date parsing code
  • Added two more date format masks to the date parser

26/03/2009 (v4.3):

  • Fixed a bug that made the datePicker instantly dissappear whenever the no-animation instruction was used

23/03/2009 (v4.2):

  • Fixed a bug that made the script unresponsive when attempting to set the format masks
  • Added the “destroyDatePicker” and “cleanUp” methods to the datePickerController Object

17/03/2009 (v4.1):

  • Fixed the “firstDayOfWeek” bug
  • Fixed some incorrect ARIA id references
  • Changed the code to return a localised date should a language file have been explicitly set and an English date if none was set

10/03/2009 (v4.0):

  • Bug fixes

05/03/2009 (v4.0b):

  • First public beta release – fingers crossed

Tags: calendar, datepicker, javascript, unobtrusive

Previous Comments ~

Brian Paterson · http://www.genesysosp.com
#1 · Friday February 6, 2009

Bloody marvelous. I never thought to consider your approach.

I inherited a mess and have been looking for a better way out of the mousetrap. Although from a certain point of view, inheritance is probably not a good word to use…

One thought – optional “today” as there are several from-to uses that we make available and while we do see the “to” differing from “today”, it would be a grand place to start.

I will check back here in a week or so.

Cheers!
Brian

Brian Paterson · http://www.genesysosp.com
#2 · Friday February 6, 2009

It dawned on me that the comment was obscure – the “to” date needs to be acted upon, as does the “from” date. Preloading the “to” date as “today” and having the user go on to select the next action is where I’m heading… Saves annoyed users – “Of course I mean today…” usually followed by %^#$.

Nathan Smith · http://sonspring.com/
#3 · Sunday February 8, 2009

This is by far the best calendar solution I’ve ever used. I appreciate that you have continued to maintain it, and have enjoyed watching the improvements through the years. Keep up the great work, and thank you for making this (and the table sorter) available for public use.

Nicki · http://www.nickibutler.com
#4 · Sunday February 8, 2009

Firstly, thank you so much for making such a clean, functional date picker! I searched through a bunch of junk for a week before I found this and I’m dead-set on using it for an online order form I’m currently working on. I’m a js n00b and so far your comments throughout the code have been very helpful as far as figuring out what means what, what does what etc. However, I’m having major issues figuring out how to disable the dates I need to. Basically, I need to disable any dates before the date two days after todays date (for example, it’s the eighth, so I would need every day before the eleventh to be disabled, for the ninth any dates before the twelfth disabled, and so on). I feel like this should be really simple but after five hours of hopelessly staring at variables I figured I’d just ask. Any hints, input anything would be extremely helpful. Thank you!

Will Martin
#5 · Monday February 9, 2009

It may be keyboard accessible — in the sense that it can be controlled using keyboard shortcuts — but alas, it’s not screen reader accessible.

I was really hoping that it would work with screen readers, but when I tested it just now (using FireVox) I ran into some major problems.

1) When navigating through the document, the screen reader does not announce the existence of the calendar icon that triggers the date picker. A blind user won’t have any idea that the date picker is there.

2) On the other hand, that’s probably a feature, because when you do trigger it, the resulting audio goes on for two minutes and thirty seconds before it finishes, during which time the user will have no clue what it is. I recorded it for you — download the 3 megabyte MP3 and listen for yourself. It’s a tad repetitive. Most of that it is repetitions of the words “new” and “slash VT pitch”.

3) Once the date picker has loaded, it’s fully possible to control it via keyboard. But doing so generates no audible output.

So, any blind user who manages to find the date picker, open it, and sit through the resulting welter of gibberish, is not actually going to be able to select a date using it.

I don’t have a copy of JAWS or NVDA handy, so I can’t tell you for sure what they’d make of it. I’m guessing they’d make hash, though.

I don’t mean to criticize too much. It’s a fine piece of user interface work, and getting JavaScript to play nice with screen readers is freaking hard. I like the script a lot, and I would love to use it. But … my workplace has legal obligations regarding accessibility for the blind, and this script can’t meet them.

frequency decoder
#6 · Monday February 9, 2009

@ Brian: Hi Brian, the datePicker will use the associated form element(s) value to calculate the date it uses at launch. You can always disable the “today” button by using the “no-today-button” class.

@ Nathan Smith: Hi Nathan, nice to hear from you and thanks for the support.

@ Nicki: Hi Nikki, there are two ways to do this:

1. Calculate the date server side and use this date within the “range-low-” className e.g. “range-low-20090304”
2. Calculate the date using javascript and call the setRangeLow method.

@ Will Martin: Hi Will, the datePicker was never intended to work with screen readers.

I never even thought about adding ARIA roles/states etc as I was of the opinion that screen-reader users would use the associated form input to enter the desired date (without ever activating the datePicker).

If you have an example of a datePicker that is screen-reader accessible, please drop me a line as I’d love to have a look at how it was done and, if possible, update the code to be screen-reader friendly.

Regards,
Brian

Curtis Ling
#7 · Monday February 9, 2009

Where’s the download link? Can you send me a copy of v4 ?

Daniel W.
#8 · Monday February 9, 2009

This is a very nice looking calendar, thanks for making it publicly available!

I’m using Internet Explorer 6 sp3 (Here’s the big full version number: 6.0.2900.5512.xpsp_sp3_gdr.080814-1236) and it looks like the pop-over calendar no longer pops over IE6 select boxes — the select boxes show through.

If you look at the new demo:
http://www.frequency-decoder.com/demo/date-picker-v4/

Go to the “Split Input DatePickers” section, and click the very last calendar icon in the section. The calendar pops up and the tip of the “Year” select box bleeds through the calendar panel.

I’ve observed this same behavior with DatePicker v4.4, I believe that IE6 SP3 broke this. When I inspect the DOM concents using IE Developer Toolbar, I notice that the IFRAME with DOM ID iePopUpHack is not present.

In using version 4.4, I’ve tried forcing the iePopUpHack to always appear (removing the @cc directives and JScript version checks) such that the iePopUpHack IFRAME appears, but the frames still show through.

Have you observed this behavior?

Thanks,
Daniel

Lance Li
#9 · Wednesday February 11, 2009

hi, does it have a feature ,if i want select month only.it’ll be like this 02/2009

Paso
#10 · Wednesday February 11, 2009

Very good datepicker, thanks for jou job !
Using the demo version i found a little problem: when insert a valid date value in the code, viewing the page the focus is on the date field in the form, not good if this field is at the bottom of the form.

Lee
#11 · Wednesday February 11, 2009

I cant wait to give this a go.. Great work Brian.

It will be very interesting to see how it performs compared to the old version. I have a page without 50 date pickers on it and this causes a browser lag of ~2secs to render in FF3.

Lars
#12 · Thursday February 12, 2009

Nice script. I would mail you the german languagefile, but I couldn’t find any contactinfo on your website. If you want to include the file in the next release, send me a mail.

frequency decoder
#13 · Thursday February 12, 2009

@ Curtis Ling: Hi Curtis, I’ll add a download link when the scripts been debugged a bit more (it’s not ready for primetime just yet).

@ Daniel W: Hi Daniel, the SP3 update to IE6 changed the JS version – which is what was throwing the code. I’ve fixed it for the next release.

@ Lance Li: Hi Lance, sorry mate, the datePicker needs a date to have day, month and year parts. why don’t you just use a select list with the values 1 – 12?

@ Paso: Hi Paso, It’s a bug I hope to have fixed next release.

@ Lee: Hi Lee, if they are popup datePickers then the lag shouldn’t exist with the new version. If the’re inline then, of course, they all have to be created.

@ Lars: Hi Lars, hold off on the language files as there may be more text to translate as I’m currently integrating screen reader friendly functionality into the script.

jblomberg · http://n/a
#14 · Thursday February 12, 2009

In the this.reposition function, this seems to work better for setting the top of the window when you have a tiny page in a tiny window. It keeps the datepicker from showing up way below the icon.

o.div.style.top = Number(parseInt(trueBody.clientHeight+scrollTop) < parseInt(osh+pos1+elem.offsetHeight+2) ? ((parseInt(pos1 – (osh + 2))) < 0 ? parseInt(pos1) : Math.abs(parseInt(pos1 – (osh + 2)))) : Math.abs(parseInt(pos1 + elem.offsetHeight + 2))) + “px”;

e.g. load code with only 3 date pickers in 3 paragraphs in a very small window and notice where the datepicker shows up:

input type=“text” class=“dateformat-m-sl-d-sl-Y disable-days-2” disabled id=“anotherDate” name=“anotherDate” value=”“ maxlength=“10”

jblomberg · http://n/a
#15 · Thursday February 12, 2009

Oh, and if the “disabled” attribute is on the input field, it would be nice to not have the calendar icon be able to take focus. It’s great that the picker doesn’t show up when clicked, but to avoid it all together would be even nicer!

(P.S. I love this date picker! It’s SLICK! Great job)

Jay
#16 · Thursday February 12, 2009

I need an RSS feed so I know when this is ready. Just happened to stumble upon this update.

jblomberg · http://n/a
#17 · Thursday February 12, 2009

When the input field is disabled, you can disable the calendar icon from getting focus by adding this is datePicker.prototype.createButton:

if (!this.getElem().disabled) { but.href = “#”; }

and adding the first a.date… line below to the css:

/* The “button” created beside each input for non-static datePickers */
a.date-picker-control,
a.date-picker-control:link,

It might be nice to have a formatter flag to keep the icon from getting focus so the user can tab from field to field without having the calendar icon get focus (for those people who don’t want keyboard accessibility to the datePicker).

jblomberg · http://n/a
#18 · Thursday February 12, 2009

Changing createButton() to have this code allows you to add an option that disables focus on the date picker calendar icon, yet you can still use a mouse to click on it.

if (!this.getElem().disabled && !this.noCalFocus) { but.href = “#”; }
frequency decoder
#19 · Friday February 13, 2009

@ jblomberg: Hi jblomberg and thanks for the suggestions. I’ll roll them into the latest version in a few weeks when I’m back from vacation (the code has changed dramatically over the last few days).

@ Jay: Hi Jay, there is an RSS feed, just click the RSS icon in the location bar of FireFox.

Jay
#20 · Saturday February 14, 2009

Fail ;)

julien · http://www.theautopress.co.nz
#21 · Tuesday February 24, 2009

Hi, i’m using this datepicker on two differents text field on a same page. I have added some javascript to disable some dates when the page is loaded.
What i want to do is :
when you select a date one the first datepicker, if the date selected is a friday, i want to disable a date on the second datepicker. I have made some javascript code to change the class name of the input field, which is fine.
But the calendar doesn’t display the date that i want disabled, only the one that have been define on the first page load.
Is there any way to reload the calendar without refreshing the page?

Sam · http://defunc.com
#22 · Tuesday February 24, 2009

Just wondering when a release is looking like it will make it off the ranks? Would love to use this script but cant seem to get it to work just saving down the demos page.

Many thanks,

frequency decoder
#23 · Wednesday February 25, 2009

@ Jay: Actually Jay, you’re right… I should really make the RSS button a part of the design and not expect people to find it using the browser…

@ Julien: Hi Julien, please read the section “Disabling date selection programmatically”.

@ Sam: Hi Sam, the accessibility enhancements meant that I had to rewrite large portions of the script but I’ll be releasing something this week. Thanks for the interest.

jblomberg
#24 · Friday February 27, 2009

Hey, just checked out the latest demo. It’s looking good! I don’t know if you misunderstood one of my suggestions, or decided that it wasn’t a good one and implemented something different re: Disable/enable demos.

I have a case where I need a date picker that works (e.g. you can click on the calendar icon to get the picker), but I don’t want to be able to select that icon via the keyboard (e.g. tabbing should skip the icon and go to the next field). This allows a person to type in a date, hit tab and be in the next typing field. That’s the case where I suggested you could leave the “but.href =”#” off of the calendar icon via a ‘noIconFocus’ option or something. Well, if you don’t implement it in your code, I’ll know how to do it anyway. Looking forward to the release! Cheers!

Conrad
#25 · Friday February 27, 2009

I would like to use it in a RIA where this calendar should be one of the main interaction elements to jump within a schedule. I used the YUI Calendar within the last half year of implementation but the abilities to show the week numbers and select dates outside the current month convinced me to use your calendar. Unfortunately my euphoria was damped because I don’t see any possibilities to communicate “from outside” with the calendar. In fact, i use a lot of custom classes (framework is mootools) and would like to send events (or a method) to the calendar to switch the month (highlight days, weeks…) – on the other side, if I click the calendar, the schedule should show the clicked target…
Do you have any idea how I could communicated between these instances (maybe with custom callback functions) ?

Lily
#26 · Saturday February 28, 2009

I think this is great, how can i get it???

frequency decoder
#27 · Monday March 2, 2009

JBloomberg: Hi , in fact, you can use the “buttontabindex” option (passed using JSON) to stop the activation button from being added to the document tabindex.

Conrad: Hi Conrad, there’s a JavaScript API but I just haven’t got round to detailing it (or the callback events) – something thats priority for this week. Here’s a quick list of the available methods:

addEvent, removeEvent, stopEvent, show, hide, create, repositionDatePickers, printFormattedDate, setDateFromInput, setRangeLow, setRangeHigh, parseDateString, setGlobalVars, dateValidForSelection, addDisabledDates, setDisabledDates, disable, enable

@ Lily: Hi Lily, I’ll be putting up a download .zip this week.

jblomberg
#28 · Monday March 2, 2009

Could you fill me in on how the ‘doctype’ statement is related to how the datePicker is displayed? When the statement is omitted, the font sizes are Really Big. I’m asking because the pages I’d like to implement the datepicker on are not XHTML and would require A Lot of Work to make them so. (When the statement is included with what I’m working on, the datePicker looks right, but the page’s layout change too much to be useful anymore).

frequency decoder
#29 · Tuesday March 3, 2009

@ jbloomberg: Not having a doctype means that the document renders in quirksmode. When in quirksmode, TDs have a font size of 80% of the default browser font size (usually 16px). Try setting a non-em based font size directly on the CSS declaration for the TD to avoid the problem.

JBlomberg
#30 · Tuesday March 3, 2009

Cool. OK. Found the Quirksmode stuff in the css. Thanks. I think I have just one last question: onchange(). It seems that using the datePicker to change the date isn’t triggering the onchange=“functionname()” parameter for the input field. I’m not sure what I’m missing to have that happen.

Shawn
#31 · Tuesday March 3, 2009

Hi,

Some date pickers these days are able to show multiple months at once
such as the ones used here:
http://www.travelocity.com/

This date picker is much more attractive of course, but doesn’t seem to have
that functionality – or am I missing something? I really like this datepicker
but having 2 or 3 months come up at the same time is pretty important to us
Is that planned? Or is there some way to make that work?

frequency decoder
#32 · Wednesday March 4, 2009

@ JBlomberg: If an input’s value is changed using JS, the onchange event never fires. I would have to manually create and fire the event in the datePicker code (which is frowned apon). You can use both the input onchange event and the “dateselect” callback to intercept all change events on the input.

@ Shawn: Hi Shawn, I have no plans to support the display of multiple months. Sorry to disappoint you!

Kevin
#33 · Wednesday March 4, 2009

Hello.

I don’t see a place to download these files. Am I missing something?

Thanks.

frequency decoder
#34 · Wednesday March 4, 2009

@ Kevin: Hi Kevin, read the section “demo, downloads & updates”. I'm currently trying to find the time to iron out the (minor) kinks, compress the javascript and package a complete download - unfortunately, (paid) work is, as usual, rather full-on and the immediate priority.

I will publicly state though that a download will be forthcoming before March 9th - this way I have no excuses.

Thanks for the interest.

JBlomberg
#35 · Wednesday March 4, 2009

All is good except that it seems you can’t use parenthesis in the name parameter. e.g.

input type=“text” name=“propertyValue(relStfPsnOid_psnDob)” class=“dateformat-m-sl-d-sl-Y …. etc.

My guess is it is messing up the regular expressions in the datepicker code. Am I right? :-(

frequency decoder
#36 · Thursday March 5, 2009

@ JBlomberg: Just give the input a unique id attribute.

JBlomberg
#37 · Thursday March 5, 2009

My mistake. The ‘name’ parameter can have parenths in the quotes, it’s the ‘id’ parameter that can’t. The jsp/struts stuff I’m working with needs the parenths in the ‘name’, but not the ‘id’, so I’m OK with this issue. I don’t know if it affects anyone else’s implementation of anything. Technically, you should be able to have parenths in the ‘id’ string.

Looking forward to the final release!!! :-)

JBlomberg
#38 · Monday March 9, 2009

I tried changing the en.js file to change the first day of the week to Sunday. Any changes made to any of the text strings in the file are picked up (e.g. month names), but the firstDayOfWeek remains 0. Bug? Or am I doing it wrong?

var fdLocale = {
firstDayOfWeek:6,
. . .

Thanks!

Update by f.d: Bug, I’ll fix it when I get back from vacation next week. Thanks for the info.

Drew
#39 · Monday March 9, 2009

Great widget! I was trying to implement some global variables, but FireFox (3.0.7) reported an error. I believe toLower() should be toLowerCase() on lines 81 and 213. I changed the one on 81, which caused FireFox to have an “unresponsive script” error, and gave up on trying the global variables after that.

In the end, I determined your script won’t work (or is at least too much work right now) for my case (CakePHP names date automatically and doesn’t allow me to manually override the ids which I’m very upset about), but thought I’d share my findings.

Keep up the great work!

KP
#40 · Tuesday March 10, 2009

There seems to be an issue in ie7, if the datepicker is hidden at any point (display:hidden) and then unhidden it doesn’t work. Works fine in firefox though in this case.

frequency decoder
#41 · Tuesday March 10, 2009

@ JBlomberg : Hi JBlomberg, I’ve altered the code to allow the downloading of the en.js file, so you can now set a bespoke firstDayOfWeek.

@ Drew: Hi Drew, I’ve fixed the “toLower” sillyness and the setGlobalVars method works as intended. In fact, I added this method especially for the CakePHP guys – it’s just I never tested the method in question.

@ KP: Hi KP, I don’t understand, do you use JS to dynamically show/hide the datePicker?

pillar
#42 · Tuesday March 10, 2009

Great looking script, I am having one critical problem though:

1) The month is displayed correctly as March, but the generated date has the month as April

pillar
#43 · Tuesday March 10, 2009

1) The month is displayed correctly as March, but the generated date has the month as April

Upon further testing I found that it only occurs when the month is “n” in the dateformat. If “m” is used, it works correctly.

Drew
#44 · Tuesday March 10, 2009

Looking forward to the next revision of your code.

Also, I got ambitious and Googled CakePHP and Frequency Decoder’s date picker and found a solution to integrating your date picker with Cake:

http://bakery.cakephp.org/articles/view/using-the-unobtrusive-date-picker-widget-in-cakephp

Comment 9 works, but I changed the 2nd param to null (4th param on year). Hope this helps those working with Cake.

frequency decoder
#45 · Tuesday March 10, 2009

@ pillar: Hi pillar, I’ve fixed the bug. Thanks for the info…

@ Drew: Hi Drew, I’ve updated the download with a few bug fixes. Thanks for the CakePHP info.

Gabriel Read
#46 · Wednesday March 11, 2009

A truly elegant script, thanks and congratulations.

1 thing to note, while integrating the calendar into a layout I had no control over I was receiving an error regarding the following line:

if(el.id && el.id.search(reg) != -1)

The error was stating the el.id.search was not a function and the calendar wouldn’t dissapear – after adding an alert it was found that el.id existed, but was an empty string hence the error. Making the following change fixed it all up;

if(el.id && el.id.length && el.id.search(reg) != -1)

Probably not the best solution, but it may help someone, somewhere… maybe.

Alfred Vorsselman
#47 · Thursday March 12, 2009

Very nice script!

I do have one problem I can’t solve by myself.

When I use the parameters “dateformat-l-cc-sp-j-sp-F-sp-Y” and “statusformat-l-cc-sp-j-sp-F-sp-Y” (notice that the relevant parts are identical) together with the language file nl.js, the date on the statusbar is nicely translated into Dutch, but the output date in the form is still presented in English.

I hope that you can give me some advice on how to solve this.

OS: Windows XP
Browser: IE, FF and Safari

Krish · http://www.focus.co.id
#48 · Thursday March 12, 2009

Halo, i have sent you ID language via email today.
I have a question, how to disable the “input text” ONLY, and NOT the “calendar icon”. I have tried to disable the input text but the result is the icon become disabled too.
My reason is I want to receive entry from the calendar only and not the input text (which is maybe user enter value in the wrong format).
Please help, thanks

David
#49 · Friday March 13, 2009

Hi, great script, thanks!

I am trying to see if this fits what I need to do and customizing it, however I am having a real issue with the firstDayOfWeek. I need it to be Sunday and I can’t get it to work. I made a separate language file, which loads fine (tested it by renaming one of the days in there), but no matter what value I specify (yes, it’s commented out) for the firstDayOfWeek var (should be 6), first day of week is still Monday. I hacked it directly into datepicker.js with this.firstDayOfWeek = 6; inside the datePicker function and it worked, but I would like to use the datepicker.packed as I need to save on download size…

Any tips?

Thanks!

Phill
#50 · Saturday March 14, 2009

Oddly enough, the following block of code would error for me when run through JSmin.

tmpDate.setFullYear(tmpDate.getFullYear() + +acc.year);
tmpDate.setMonth(tmpDate.getMonth() + +acc.month);
tmpDate.setDate(tmpDate.getDate() + +acc.day + (7 * +acc.week));

I solved it by removing one of the double +, but I dont know if it actually is a bug or required to make something work properly? Calendar still seems to function…

Campbell Harris · http://www.relaxingjourneys.co.nz
#51 · Monday March 16, 2009

G’day from NZ. Looks great but…can this script be configured to disable any dates in the past, present and say the next 3 days? This would make it perfect for me. Odd’s say it does, but just wanted to check?

JBlomberg
#52 · Monday March 16, 2009

This fix to the firstDayOfWeek-not-working bug in the language .js files is to change

function datePicker(options)

to initialize the var this way:

this.firstDayOfWeek = localeImport.firstDayOfWeek,

Drew
#53 · Monday March 16, 2009

Hi. I wanted to know if it’s possible to call the datepicker after the page has been loaded.

In my case, I am dynamically creating the input fields (kind of like an in place editor), and would want the datepicker to be created once the user clicks on the date.

Any thoughts?

Xavi Drudis Ferran
#54 · Tuesday March 17, 2009

Hello, and thanks a lot for your date picker.

We’re considering using it in a commercial program, but it seems to be incompatible with cc by-sa . Most other components are Apache2, BSD or MIT like licensed, but one is CDDL, one is CPL and one is the mysql connector licensed under GPL plus an exception. The exception is for FOSS developers using some of a list of licenses that does not include cc-by-sa (but includes CDDL and CPL).

Mysql connector licensing:
http://www.mysql.com/about/legal/licensing/foss-exception/

CPL: Common Public License (incompatible with most other)
http://www.eclipse.org/legal/cpl-v10.html

So we would like to be able to integrate your date picker in our web application under a
compatible license (CPL, for instance), or we’ll have to settle for some inferior date picker. Would you be willing to license it under CPL ?

Thanks in advance.

frequency decoder
#55 · Tuesday March 17, 2009

@ Gabriel Read: Hi Gabriel, thanks for the fix, I’ve rolled it into the latest download.

@ Alfred Vorsselman: Hi Alfred, I’ve changed the way that dates are returned to the server. If a language file has been explicitly defined, the date is returned in that language. If the detect-locale functionality has kicked-in and downloaded a language file, the date returned to the server is in English (which means you know that all non-numeric date parts will be in English and not a random language).

@ Krish: Krish, what you are asking is insane. It’s really not accessible to disable all text input’s just in case the user decides to enter a date in a format of their choice). You can use a callback function to disable the input if you really must but you’ll have to work that one out yourself…

@ David: Hi David, the firstDayOfWeek bug has been fixed within the latest release – honestly!

@ Campbell Harris: Hi Campbell, read the section “Disabling date selection” please.

@ JBlomberg : Hi JBlomberg , in fact, it’s a bit more complicated than that (but thanks for the attempted fix anyway) – I’ve fixed it in the latest release.

@ Drew: Hi Drew, just call datePickerController.create() after the input’s have been added to the page.

igor
#56 · Tuesday March 17, 2009

It looks pretty fine, but has one major bug! If you use it in “inline” mode and then click on any date, and afterwords try to change months; go to previous or next month; you get every second month. It is really annoying, because you can’t return to month (date) you clicked the first time, until you click some other date. Fix it any time soon? tnx, it is really good stuff and I will try to use it on my NGO project

David
#57 · Wednesday March 18, 2009

Thanks for firstDayOfWeek fix! Works for me now.

igor
#58 · Wednesday March 18, 2009

Also to add onmouse events for specific dates, because when using in inline mode it would be nice to have for example tooltip shown on onmouseover or modalbox shown on onclick. For example to be able to add “{onmouseevent}-{date}-params-callToSomeJSFunction(‘data’)” and so on.

frequency decoder
#59 · Wednesday March 18, 2009

@ Xavi Drudis Ferran: Mail me on frequency (dot) decoder (at) gmail (d0t) com and I’ll give you the license you require.

@ Igor: Hi Igor, you need to state the browser you are using as I can’t reproduce the bug using Firefox. There’s a “cb_dateselect_” callback function that you can hook the modalbox into but theres currently no way to hook the mouseover events to a tooltip (in fact, this could be achievied by adding mouseover/out events to the table within the “cb_create_” callback function).

@ David: Hi David, glad to help.

chris beck · http://www.directra.com
#60 · Thursday March 19, 2009

I have a popup form (retrieved via ajax) and I want to use the picker on a control on that form. Can i just call datePickerController.create(); after the ajax page is loaded? It appears to work. It was already called once on window.load as part of datepicker.js. Can I assume the window.unload datePickerController.destroy() will take care of cleaning the page up? Or do I need to call some function each time the ajax popup is dismissed? Thanks so much.

David
#61 · Friday March 20, 2009

Hello,

I have a similar question to Chris Beck’s above. Mostly I’d like to know how to dispose of a previously create datePicker before creating another one, or at least understand if there’s a need for it. What I’m trying to do is a bit tricky.

Let’s say I have a date field that uses the in-place editor from Scriptaculous. This means that until I click on the field, the input doesn’t exist in the DOM, so the date picker cannot be created (using datePickerController.create()).

Here’s what I’ve figured out so far (and perhaps will find a better idea later): in the callback for the in-place editor, I have a function that goes and adds the proper dateFormat class to the input after said input gets created, then I run datePickerController.create().

This seems to work fine, but here’s the deal: as I am having the trigger icon appear in another div, when I close that instance of the in-place editor (input disappears from the DOM) and then click on it again, I get a second datePicker icon. The second one works with the new instance of the field, but nothing happens when I click on the still remaining icon from the first datePicker.

Now I’m not asking for troubleshooting of my stuff, but I’m just wondering what I should be doing with a previously existing instance of datePicker in this condition (doesn’t look like there are dispose or destroy methods). Getting rid of previous icons is an easy thing, but am I piling up tons of instances of datePicker when doing what I’m doing?

Thanks for any help.

David
#62 · Friday March 20, 2009

A bug report: when passing the “formats” value for the global vars, either directly in the script tag or as a json object (as explained in the example above), it causes the script (datepicker.packed.js) to become unresponsive. This is in latest version of Firefox.

David

Update by f.d: Hi guys (David and Chris), sorry for not getting back sooner! I've added two public methods to the datePickerController Object that enable you to remove datePicker instances from both the DOM and memory.

The first method datePickerController.destroyDatePicker("the form element id") enables you to remove a single, known datePicker instance while the second method datePickerController.cleanUp() will loop through the current list of in-memory datePickers, check their associated form element still exists and if not, remove the datePicker instance.

Hope this helps with your respective implementations.

JC
#63 · Monday March 23, 2009

re: “@ Campbell Harris: Hi Campbell, read the section “Disabling date selection” please.”

Any way to disable all previous days to today, as in dynamically calculate current day? [eg. ‘disable-19000101-today’, or even ‘disable-19000101-today_plus3’ and even more fantastic ‘disable-19000101-today_plus3working’] otherwise would i need to do some manual js calls onload to calculate current day and then insert className— in fact would that even work?

JC
#64 · Monday March 23, 2009

re: #63

Sorry my bad. just came across ‘range-low-...’

Great job on this date picker widget by the way.

Rich
#65 · Tuesday March 24, 2009

Just effin beautiful! So easy to put use. I’ve never felt such joy from a widget.

Craig Beaumont · http://www.integrat.co.za
#66 · Wednesday March 25, 2009

Love, this and have used it before – the only thing missing is the ability to also select a time as part of the date.

David
#67 · Wednesday March 25, 2009

FD, is that cleanUp method new? I tried to use it before (after modifying the JS file to add it as a method to call), but it didn’t work before and doesn’t seem to work still.

Here is why I think it doesn’t work: the first time the instance of the datePicker is created, the created icon has an id of “fd-but-fdDatePickerInput-0” and the input receives “fdDatePickerInput-0”. Then, the input is eliminated from the dom (and I clear out the div that was the target for the calendar icon), then I launch the routine again and the cleanUp method is using before the datePickerController.create is launched. This second time the icon gets an id of “fd-but-fdDatePickerInput-1”, and the input gets “fdDatePickerInput-1”. And so on…So I could be wrong but this makes me think that the previous instance is still in there somewhere…

David.

David · http://travelwithdave.com
#68 · Wednesday March 25, 2009

This is awesome. Thank you very much for makingit available.

Sean
#69 · Wednesday March 25, 2009

This is a nice-looking control! Thank you for making it available to the community.

It appears to me that when no-animation is used in the class property, pressing enter to display the calendar control instead selects the current date and populates the textbox control. My hunch is that the problem might be the visible check in the onkeydown function.

Tried to confirm, but I’m still looking for a nice way to debug JS (IE8 and Firebug are patience-trying). Maybe this is related to the comment in datepicker.js about IE fireing the keydown event faster than the JS engine can update the interface, but it’s happening in FF as well.

And again, nice control!

Rich
#70 · Wednesday March 25, 2009

In FireFox 3 i am getting:

uncaught exception: Index or size is negative or greater than the allowed amount (NS_ERROR_DOM_INDEX_SIZE_ERR)
http://localhost:3933/js/datepicker.js
Line 46
Firebug shows this line: scriptInner = script…replace(/\s+$/, “”), in both the packed and nonpacked.
Could be a bug in the script? I’m sending it a date formatted as “mm/dd/yyyy

frequency decoder
#71 · Thursday March 26, 2009

@ David: Hi David, yep, I tweaked the cleanUp method and made it public. It should work within the latest release for you. I also added a destroyDatePicker method to enable you to destroy known, named datePickers.

@ Sean: Hi Sean, you found a bug! I’ll look into it. Thanks for the warning…

@ Rich: Hi Rich, have you linked the datepicker.js file within the HEAD of your document?

Thanks for the feedback guys, it’s much appreciated…

Rich
#72 · Thursday March 26, 2009

Yes, the js file is ending up in the head of the document. All of this is in a master/content page set-up in asp.net but the browser is seeing the js in the head. Would this error occur b/c the form field is rendered prior to the js file? I am using a script tag to link to the file.

David
#73 · Thursday March 26, 2009

FD, I saw your post about the new methods, but as I mentioned, the cleanUp method doesn’t seem to work as the new datepicker input and icon IDs get incremented with each new datepicker despite the use of the cleanUp method between each. Perhaps the increment is normal though. I cannot tell for sure. Perhaps there is a way to see a list of current datePicker objects in memory but I do not know it, yet.

I cannot use the destroy method on a known datePicker because it’s all dynamic. I just wanted to be able to clear all the “dead” ones before launching the create. It’s not a major thing. I’m not sure what impact it would have but there’s a possibility that this would be used very often in the course of a day without refreshing the page.

Update by f.d: Hi David, the form element ID's are incrementing naturally. If a form element does not have an ID assigned to it, the script assigns a generic one that includes a trailing Integer. This Integer value is incremented after each use, which is why you are seeing different ID's on the creation of each new datePicker.

Alex
#74 · Friday March 27, 2009

Is there any way to disable specific days? i.e all Saturdays. That would be a great addition. Something along the lines of;

setDisabledDates(inpID, dts)

where dts is an array of days

David
#75 · Saturday March 28, 2009

FD, thanks for your answer. I couldn’t tell if the increment would happen anyway or if it was due to the fact that other instances were still in memory.

I got this to work exactly as I needed.

Thanks for all your work,
David

régis
#76 · Monday March 30, 2009

Thanks for your work, it’s great
Hi, there is a bug with the y dateformat, when you have dateformat-d-sl-m-sl-y and select a date it’s ok, but when you do it again, the js skip the first char of the year, so 19/03/09 is changed to 19/03/9 in the input

jochen · http://jochenpreusche.de
#77 · Monday March 30, 2009

Good job! Thanks for sharing!
But:
localisation could be better. We germans don’t say stuff like:
Freitag, 3^rd^ März
we’d rather say: Freitag, 3. März

frequency decoder
#78 · Monday March 30, 2009

@ Alex: Hi Alex, please read “Disabling day selection”.

@ Régis: Hi Régis, I’ll look into it a.s.a.p. Thanks for the warning.

@ Jochen: Hi Jochen, all localisation is up to the user. The “rd” is present in the date as I’ve used the “S” date format which, to quote from the article, creates an “English ordinal suffix for the day of the month: st, nd, rd or th”. I imagine you wouldn’t use this format unless the datePicker was specifically set to the English locale – something I didn’t do for the demo.

So, to recap, don’t use the “S” date format specifer unless you explicitly use an English locale.

Hope this clears things up for you.

hidden
#79 · Tuesday March 31, 2009

In the Javascript API are some funktions to show or hide special days, but I didnt saw one to highlight a special day.
Is there a feature to highlight special days, maybe in basic Colors?

frequency decoder
#80 · Wednesday April 1, 2009

@ Hidden: Hi Hidden (what’s so hard about typing in your real name?), there are two ways to do this. The first and easiest way is to use the className hooks assigned to each TD cell to style known dates. For example, to style every Christmas day, you could add the following to your site’s CSS file:

.mmdd-1225 { your styles here… }

To style only Christmas day 2009, you would define the class:

.cd-20091225 { your styles here… }

If you need to style dynamically calculated days, the “redraw” callback can be used – in fact, one of the last demo’s almost shows how this can be done (the demo disable’s Easter Monday but you can use the return Object to style individual dates instead).

Regards,
Brian

AndyH
#81 · Monday April 6, 2009

I found a small bug in datePicker.prototype.setDateFromInput that I can’t seem to fix. When I load the datepicker with a defined date value, it does load the date properly, but then takes over the keyboard controls until I mouseover the datepicker. Once I mouseover, I can enter text in the text fields elsewhere in my form, but until I do that, any key strokes that map to a keyboard control on the datepicker take focus away from the text fields and puts it on the datepicker.

Any suggestions? I’m using v4b2.

By the way, this widget is really awesome, thanks so much for building it.

Update by f.d: Hi Andy, an update to the latest version should fix the problem (amongst others).

AndyH
#82 · Monday April 6, 2009

Awesome, I’ll grab it now (I assume there is no download, we just grab it from the demo page?). Thanks!

AndyH
#83 · Tuesday April 7, 2009

f.d: I upgraded to the latest version, and still have the same problem, although there is a slight improvement. When the form first loads, the date picker still takes over keyboard controls. If I then click back in the first text field, the keyboard works as expected (I can type in the field). Any suggestions on how to prevent the date picker from taking over keyboard control initially?

Also, I’m having a separate VERY weird problem. I’m using the date picker in a Rails application, and when I load the datepicker.js file locally, I get a “titles is undefined” error. However, if I load them from your server with the absolute path (don’t worry, this is just for testing), it works.

I’ve stripped absolutely everything out of my application, and this is driving me nuts. I can’t figure out why loading the file locally would have any impact.

Thanks!

AndyH
#84 · Tuesday April 7, 2009

Hmm, previous comment seems to have disappeared. f.d., I grabbed the new file, which is giving me a “titles is undefined” JS error. If I load the file directly from your server, it works fine. I’ve downloaded the zip file, done everything possible, but if I load it locally off my server, it results in the JS error.

Any insight? It’s a Rails app, by the way…

Update by f.d: Fixed. The problem was that the language file was being included after the datepicker.js file and not before.

therealvibe · http://marandi-aruba.com/preview/
#85 · Tuesday April 14, 2009

f.d: I am using the latest version 4.4. I have set this reservations form.
But the start date and end date are not close to eachother. See this form.
In IE7 the icons are just where they need to be after the input field on the right side. But in FF Chrome Opera and Safari the calendar button is just on top on the 2 first fields. Please let me know if there is a way to make ik behave for FF Opera Chrome Safari like IE7 is behaving.

http://marandi-aruba.com/preview/

frequency decoder
#86 · Monday April 20, 2009

@ TheRealVibe: Hi, I just checked in Firefox and the buttons lined up perfectly. Perhaps you managed to fix the problem when I was away on holiday?

Boysenberry Payne · http://habitatlife.com
#87 · Tuesday April 28, 2009

I wanted to mention that the languageInfo variable causes en.js to be requested even though there is no en.js file in the zip I downloaded. I solved this call by surrounding the block in question with an if statement as languageInfo != “en”. I believe this surrounds lines 55-76 aprox. You might want to add it to the source file : datepicker.js…

Beautiful code though, thank you for your effort. If I ever get a chance to pay you for your effort I will….

frequency decoder
#88 · Wednesday April 29, 2009

@ Boysenberry Payne: Hi, in fact, the download should have the en.js file and it’s ommission is an error on my part. I’ll re-zip things today to include all of the latest language files. Thanks for the info.

Oliver Sharpe · http://..
#89 · Thursday April 30, 2009

Hi, I really enjoying reading your articles, I am a beginner learning JS.
I think your date picker is great, I have been trying to add it to a website which I’m developing, I don’t really need the date picker functionality, I just want the calender to be displayed without a text input field.
Can you assist me?

John Baum
#90 · Sunday May 3, 2009

The en.js file is still missing in the zip???!!! I understand that you need time for your children, however, it is not too much to ask for a running code, and yes I know I don’t have to use your code. On the other side, you don’t have to post it and waste our time on bug searching.

frequency decoder
#91 · Monday May 4, 2009

@ Olivier: Hi Olivier, you can just cut a paste the example HTML from the text file into the HTML of your page?

@ John Baum: John, don’t be such a tool.

Oliver
#92 · Tuesday May 5, 2009

Thanks, I have managed to display the calendar as I would like, this only issues I’m having is, it is displaying March. I would like it to be on today’s date, with all of the functionality of your calendar i.e/ scroll through months etc..
You help is greatly appreciated!

Update by f.d: Hi Olivier, I'm afraid that the datePicker has been designed to be attached/associated with a form element and just won't work without one. I think you might be better off looking at something like the lite version of the zapatec calendar for your webpage - I don't think it requires a form element.

Rob F.
#93 · Wednesday May 13, 2009

One more split?
Super this calendar script! I almost don’t dare to do this, but nevertheless a suggestion/question: would be nice if it was possible to split in 4 fields: day, date, month, year.

Rob F.
#94 · Wednesday May 13, 2009

Follow up split with day field in it, I managed it with a callback function:


function showDay(argObj) {
  document.getElementById('CalDay').value = \
  datePickerController.printFormattedDate(argObj.date, 'D', true);
};

And adding an input field with id=CalDay

gabriel · http://www.spassus.com
#95 · Wednesday May 27, 2009

Hello man,

First I would like to say that I LOVE YOUR SCRIPT ! Really… I have never seing a datepicker like yours… so easy and complete…

I am having a problem with it…

I am using it in a form to search air tickets… I also used another javascript to give style to my form… after doing that the calendar picture desapeared ! It shows OK in FF3… but in IE7 and IE8 it wont show…

So… I dont want to mess with the script… I just want to add something to make the calendar appear when I click inside the input ….

I tried the following:

code removed by f.d.

Can you point me in the right direction ?:

here is the webpage I am developing: http://www.spassus.net/ecos

Update by f.d: Hi Gabriel, Internet Explorer fires onload events in reverse order which means that the jQuery script (that is enhancing the form) is actually removing the calendar button from the DOM in IE6/7/8. All other browsers call the jQuery script and then call the datePicker script (which means the calendar button does not get removed from the DOM).

To counteract this behaviour, you can always get the jQuery script's callback function (if one exists) to call the datepickerController.create(); method.

You can also remove the line addEvent(window, 'load', create); (2533) altogether from the datePicker script and just call the datepickerController.create(); method using jQuery's $.ready(); function.

gabriel · http://www.spassus.net
#96 · Wednesday May 27, 2009

It worked.. thanks man…

Just added datePickerController.create(); right before the </body> tag… thank you SO MUCH !

Nathan Mickler · http://www.groupm7.com
#97 · Thursday May 28, 2009

I need to dynamically add a new datepicker into a webpage, but can’t figure out what I’m doing wrong. The form element doesn’t exist until the person clicks the “Add Another Recipient” button, then everything is added to the DOM. When it’s added, I see the datepicker calendar icon, but the calendar object is not initialized, so nothing happens when I click on it.

What do I need to do in order to make the newly added calendar input work?

Update by f.d: Have you given the new calendar a unique ID and then called datepickercontroller.create("the ID"); ?

Nathan Mickler · http://www.groupm7.com
#98 · Friday May 29, 2009

I was using javascript to copy-and-paste code from the current DOM into itself, which prevented the datepickercontroller.create() function from working — so I changed the way that I was creating the new recipient and it works now.

Thanks for the help.

emonweb
#99 · Tuesday June 2, 2009

If would happy to provide some testing supports on multiple platforms as well as multiple browsers. thanks for the nice works.

Ed Slocombe
#100 · Wednesday June 3, 2009

Does the datepicker handle scripts that are written right-to-left? e.g Arabic. Many thanks.

celso
#101 · Friday June 5, 2009

uncaught exception: Index or size is negative or greater than the allowed amount (NS_ERROR_DOM_INDEX_SIZE_ERR) line 1

Update by f.d: Thanks for the bug report but I really need a URL in order to try to reproduce the testcase etc.

yves Dufour
#102 · Monday June 8, 2009

cannot set ‘en’ locale..

I am running with a French set browser… and I want to set the ‘en’ locale as described in this document…

I wrote the script
<script type=“text/javascript”> var myJSON = { lang" }; datePickerController.setGlobalVars(myJSON);
</script>

but I always get the French calendar…

If I need to change the local dynamically (I18n.default_locale = ‘en’)
how can I modify also the calendar language ?

thanks for your advices…

yves Dufour
#103 · Monday June 8, 2009

I wrote :

<script type=“text/javascript”>
/* var myJSON = { ‘lang’= <%= I18n.default_locale %> }; */ var myJSON = { ‘lang’: ‘de’ }; datePickerController.setGlobalVars(myJSON);
</script>
but still, it doesn’t change the locale

Q: after validation in my model, I would like to redisplay the wrong value in the input textfield … the error is detected, but the input textfield is reset to blank
is it the normal behavior ?

frequency decoder
#104 · Tuesday June 9, 2009

@ Yves: Hi Yves, pass the JSON Object between the script tag as updating the language by using the setGlobalVars method doesn’t work (the script has already determined the language and and downloaded the appropriate file by this stage). Here’s how to do it:


<script type="text/javascript" src="./js/datepicker.js">{"lang":"de"}</script>

Also, you can’t dynamically change the language after the calendars have been created – sorry!

Joe Pruett
#105 · Wednesday June 10, 2009

a nice system. i’m not sure why the default start day is monday :-).

one odd thing that may be a bug, or may be on purpose. why is the first column header not set the same as the others? no embedded span with styling so the cursor is the help icon.

Update by f.d: As all other headers can be clicked on in order to set the "first day of the week", it would be silly to let you click on the first column header as it is already the "first day of the week". Hope this helps clear things up. Oh, also, start day is (in general) Monday in Europe, Sunday in the states - and I'm European which means I opted for Monday...

Alexandre Paradis
#106 · Tuesday June 16, 2009

Just beautiful, practical, easy to use and fun !! Congratulation and Thanks a lot

Anthony
#107 · Wednesday June 17, 2009

Really slick!

I’m having the weirdest problem though- the date picker image doesn’t show up at all unless i put a “split-date” class on the input… I can’t figure it out for the life of me… any ideas?

<input type=“text” id=“anID” name=“dt” class=“dateformat-d-sl-m-sl-Y” value=”“ />

All that shows is an input field, but with the split-date, the icon suddenly shows. What gives?

Update by f.d: Is the calendar icon added to the DOM (use Firebug to inspect the DOM to try to locate the icon)? I really need a URL in order to help you.

histeria
#108 · Wednesday June 17, 2009

Hi everybody

I Have a question: can I disable all sundays, and later enable only one?
I need something like this: “disable-days-7 enable-20090628”, but doesn’t work for me.

Thanks a lot :)

Frits · http://www.cambodia-cooking-class.com
#109 · Wednesday June 17, 2009

Very, very nice datepicker. I really like your “showEnglishDate”.
But I’m wondering whether it would be possible to put that value into a hidden field. Why hidden? Well, I’m using the split-date-select method (Day, Month, Year), but I would like the output on the confirmation page to be in the English date format.
Is this possible?
Thanks a lot for this fantastic datepicker!

Update by f.d: You can use a callback function to populate the hidden field (one of the demos output's the value to the screen but it is a simple task to change the code to update a hidden text input).

Geeko · http://www.jbnet.fr
#110 · Thursday June 18, 2009

Warning !
The french version start on thursday.
In fr.js : firstDayOfWeek:3

To : firstDayOfWeek:0

The calendar start Monday !

Update by f.d: Ooooppps, a remenant of my testing... I'll update a.s.a.p. Thanks for the warning!

Frits
#111 · Friday June 19, 2009

Thanks for your reply f.d., but I’m a little confused here. I’m very unexperienced with javascript, so it’s probably quite dumb what I’m trying. I can get a text field, but the script doesn’t populate the field. Now, I think I need to specify the value somewhere. I have tried many different options, combinations etc, searched the internet, but I just cannot get it right. Here’s what I have (the text field is not hidden here for testing purposes), posted on pastebin:

http://pastebin.com/m1d90eb35

When substituting the two “p” s with “i” s, the script replaces the split-date dropdowns with the English date. Although I found that effect quite funny, it isn’t what I’m looking for.

Thanks for your help!

Update by f.d: Hi Frits, I've updated the pastebin code for you.

Alex
#112 · Friday June 19, 2009

Hi:

Amazing script, just one question, I’d like enabled dates to be OVER disabled dates … If I disable all sundays and enable on specific sunday, this sunday I want to enable is disable…

Is there any way to give more priority to enabled dates ?

Frits
#113 · Monday June 22, 2009

Thanks a million, f.d. ! It works!

Andre Vieth · http://www.ostsee-reisen.de
#114 · Monday June 22, 2009

Hello,

I’m using
document.all.errorid.innerHTML = ‘Error Message!’;
to display a specific error message if a wrong date has been selected (using the select box)

The following problem occured:
select an invalid date: Jan 31th through the select field
—> Error message is displayed through innerHTML
select a valid date: Jan 25th through the calendar
—> Error message disappears
—> Problem: an invisible calendar remains on the page, so there is no visible calendar window, however if I move my mouse over the screen, the comments of the calendar are displayed, e.g. Wednesday, or Jun 21 as if I would hold the mouse over an open calendar window

are there any knows problems with innerhtml? problems occurred in IE 8

Thanks.

Andrew
#115 · Friday June 26, 2009

Does anyone know how to disable days 30 days in the past? Like range-low-30-day. Would be great is someone helped. love the calander its very smooth.

Update by f.d Have you tried using "range-low-30-day"?

Chris
#116 · Sunday June 28, 2009

I wanted a callback to know when the buttons used to show the datepicker had been created (to add some nice tool tips using the qTip jQuery plugin).

This is how I got it working

Add this line of code at line 1470
this.callback(“button”, but);

change the regex expressions at lines 2338, 2339 and 2397 to:
…..cb_(button|dateselect|redraw|create)_…..

and you’re good to go. The callback gets the button object as a parameter.

Jon Tara · http://www.us.playstation.com/
#117 · Thursday July 2, 2009

I have a datepicker embedded in a div that is refreshed using Ajax. The icon is displayed when the div is initially displayed via a standard HTTP request. But the icon is never drawn when the div is replaced using AJAX. I’m guessing there’s some onload code that isn’t getting run.

Has anyone solved this problem?

Manuel D · http://www.manueld.com
#118 · Thursday July 2, 2009

@ Jon Tara

I had the same problem. I’ve debugged two hours to find a solution. Now, it’s here:

the if-conditions in line 1307 and in 1342 have to be commented out. then the picker works with ajax-requested html too.

good luck! :)

Manuel D · http://www.manueld.com
#119 · Thursday July 2, 2009

@Jon

Sorry, one I’ve forgotten: after the AJAX request is complete, you have to call the “create” function of the datepickercontroller!

datePickerController.create();

cu, Manuel

rufus
#120 · Sunday July 5, 2009

hello,
Loving the datepicker. But as with everyone here – I have a question :-D

I have specified a date range for a display-inline calendar – but is there a way of having the first date of the date range as the one initially selected?

Thanks,
Rufus

Update by f.d: If you set the value of the associated input(s), the calendar will automatically be focused on that day. This isn't a real solution though as it means the input's have a value - and in most cases, you wish them to stay blank, awaiting user input. I'll add some functionality to the code to do this but can't give a definite time frame for completion of the work (sorry).

Rufus
#121 · Monday July 6, 2009

Thanks for your feedback. I will be honest and say I must be a little slow as i do not know how to set the initial date value.

I did think it would be as simple as adding value=“20090501” to the input field but clearly that did not work. I appreciate that this must be really basic but if you can help I would really appreciate it.

Thanks,
Rufus

Update by f.d: Hi Rufus, I've just added code to the latest version that enables you to set the default cursor date by adding the className "cursor-YYYYMMDD" to the associated form element. See the section "Setting the default cursor date" for more information.

Jon Tara · http://www.us.playstation.com
#122 · Wednesday July 8, 2009

Manuel D wrote:

“the if-conditions in line 1307 and in 1342 have to be commented out. then the picker works with ajax-requested html too.”

Can you post the code in context? I don’t have if-conditions on those lines. I have version 4.4, which I think is the latest.

Thanks!

Mark · http://www.transparentsolutions.com
#123 · Wednesday July 8, 2009

This widget works very nicely. If you want to make the date input field read-only so they cannot type in garbage, is there a way to add in a CLEAR function, similar to TODAY that will set the INPUT area to be empty?

Update by f.d: Clearing the input fields value and then calling the setDateFromInput method should do the trick.

Frits
#124 · Friday July 10, 2009

Hi f.d.
Sorry to bother you again. You’ve helped a lot with the hidden English date field (#111). But now I’m having the problem that when people select the date in the calendar and then change the date in the dropdown list, I get two different dates (from the drop drown and the English date field).

Would be nice if the field ‘Year’ could be cleared whenever one of the other fields is changed (either ‘Day’ or ‘Month’), forcing them to choose the year again and thus updating the English date field. Is this possible?

Update by f.d: Actually, you have just found a nasty bug that I shall endeavour to fix when I get back from my vacation in two weeks time. Apologies.

Frits
#125 · Monday July 13, 2009

Wow, as a non-programmer never thought I would find a bug in a script… ;) Anyway, have a good vacation and hope to see your solution here thereafter.

Hari K T · http://harikt.com
#126 · Tuesday July 14, 2009

Wow cool work man . As a a developer I can assume the time you have spend behind this .
For now I don’t have anything for you , but just a congrats and wish u good luck.

Hari K T

Andy Johnston
#127 · Thursday July 16, 2009

had a couple of issues with the clicking outside of the opened calendar when using Mootools 1.2.3. Not sure if this is a result of changes in this latest lib?

Line 1045 of the datepicker.js I have modified to filter out the document object, which is throwing an error on the el.id.search() method (not existing):

// Are we within the wrapper div or the button while(el) { if(el.nodeName!=’#document’){ if(el.id && el.id.length && el.id.search(reg) != -1) { hideDP = false; break; }; try { el = el.parentNode; } catch(err) { break; }; }else{ hideDP = true; break; } };

MarkB
#128 · Tuesday July 21, 2009

Great job on this, it is truly a thing of beauty!

I noticed a small bug in IE, if you make a date selection in the next month or beyond, then click ‘Last Month’ / ‘Next Month’ it jumps back/forward two months not one. Not sure if this is just on the inline calendar or not, but that’s where I’m experiencing it.

Also, is it possible when using split-date to combine mm & yyyy into one, so would have one field as dd and one as mmyyyy – I’m dealing with a weird booking system where you have to pass the month and year combined.

Thanks in advance, hope you had a great vacation! Love your work.

Update by f.d: Hi Mark, you found a bug in the code that deals with inline datePickers that have the "fill-grid" class added. I'll try to fix it for the next release. Thanks for the warning.

As for the combined MMYYYY date field - it's not currently supported and would take some stern dev work to accomplish so I don't think it will make it into a future release. Apologies.

Jan Kaltoun
#129 · Wednesday July 22, 2009

Jon: me neither but the only thing you really need to do is to run

datePickerController.create();

after you’ve pasted the code to wherever you want it to be.

MarkB
#130 · Monday July 27, 2009

Hi F.D.

Apologies for posting this here, couldn’t find a contact email for you. Would you consider undertaking some paid development work? Not related to my post #128. If you could email me, I’ll give you details & example.

Thanks, Mark

Jon Tara · http://www.us.playstation.com
#131 · Tuesday July 28, 2009

Thanks, Jan – that worked for me. Didn’t need anything more than to call datePickerController.create(). I used RJS in Rails to make a call after replacing the element containing the datepicker controls.

kAYCEE
#132 · Tuesday July 28, 2009

THANKS, THE CODE IS JUST WONDERFUL AND ARRIVED AT THE NICK OF TIME.

Brad
#133 · Tuesday July 28, 2009

Out of the box the icon for opening the date picker jumps up a pixel or two in FF 3.5

All I did was download the files, put them in a sub directory in my website.
Transitional DTD, included datepicker.js and datepicker.css

The html for the input date box is:
<input type=“text” id=“blah” name=“blah” class=“dateformat-d-sl-m-sl-Y no-animation disable-drag” value=”“ />

Update by f.d: Hi Brad, I'm using FF3.5.1 and can't reproduce the pixel jump problem.

Brad
#134 · Thursday July 30, 2009

BUG:

The calendar doesn’t work when placed inside designs that implement scroll bar elements. DIV overflow:scroll; and putting a date picker inside that.

To fix IE float (same thing that Facebook.com does) we use a wrapper div and make that act as the BODY tag. The scrollbars are removed from the body. As the user scrolls the coordinate calculation for the date picker are off by the scroll amounts. When you have a scrollable item inside that fake BODY tag, it doubles in severity.

Brad
#135 · Thursday July 30, 2009

Here is the HTML I’m using (I hope this works)
The error occurs when you click on the icon to open the date picker.
You can right click, or left click.
Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1 (.NET CLR 3.5.30729)
:

Update by f.d: Please use the pastebin service to post code blocks (as mentioned in the small print above the comment textarea). Thanks, Brian.

Brad
#136 · Thursday July 30, 2009

Hey, I created the pastebin. So I found the issue and I fixed it.

http://pastebin.com/m6af5b6f3

I am using a scrollbar on the HTML element.

I ran into another problem though in IE only. It’s a generic bug in IE, not your application. If you try to use position: relative inside an element that is overflow: auto/scroll and there is a scroll bar, that element will float FIXED instead of relative. The fix is to add position:relative; to the overflow:scroll; element.

Kyle
#137 · Saturday August 8, 2009

I want to use the split-date but i want the month to show up in text format rather than numbers, when i change it to “F” it does not change, this works in the other calendars but not on the split-date. Any help? Thank

Update by f.d: I'm currently polishing a new version of the script that fixes this and a other problems. Should be tested and available later this week.

Keri
#138 · Tuesday August 11, 2009

I seem to have found a couple of IE8 quirks/bugs.

If you click the button to open the calendar more than once, click the next month/year it increments by 3 instead of 1.

Disabling dates doesn’t appear to work in IE8

Update by f.d: Hi Keri, I'll look into it for the next release. Thanks for the heads-up.

Luis Gomez · http://luisggomez.com
#139 · Tuesday August 11, 2009

If you ever try to use the datepicker while loading all your javascripts from outside the header (I load them all just beore the closing body tag), you may get this error:

“Index or size is negative or greater than the allowed amount”…

It comes from line 55 where the script scans for script tags in the header. If there are none, it throws that error.

I managed to fix it by checking whether the scriptFiles array contains more than zero elements before attempting to execute the “replace” in that same line.

See it here: http://gist.github.com/165994 (showing lines 54-56)

For the record, I’m on OSX 10.5 running Firefox 3.5.2 with Firebug 1.4.2. Prototype 1.6.1_rc3 is also being loaded in the page I’m testing.

Update by f.d: Hi Luis, I'll look into it for the next release. I'll have to change the code to look at all script tags on the page etc... Thanks for the heads-up.

Bruno
#140 · Wednesday August 26, 2009

Looks fantastic, but I feel like an idiot asking this – I must be misinterpreting something very basic on how to include the component in my application. This is what I did:

1) At the root of the application I placed your css, js, media folders and the calendarHTML.txt file from the zip.

2) Created a trivial html file (using the doctype for xhtml1-transitional.dtd).

3) Cut and pasted the code from the “Creating Date Pickers” section for the version splitting the date into 3 fields.

And here is the problem… I see the three input fields but they are unformatted and there is no datepicker icon. On further investigation, I see that the class “split-date” does not exist anywhere in datepicker.css. Looking at the css I also don’t see any of the dateformat classes like dateformat-d-sl-m-sl-Y.

Is the zip file missing files? Did I miss downloading some other files? Did I miss doing ‘something else’?

Update bx f.d: The classNames don't need to be resident within the CSS file as they are not used for layout - they are scripting hooks.

My advice is to install firebug and check to see what errors appear. Better yet, give me a URL to look at and I'll do my best to solve the problem.

P.S. I'm in the process of writing the new article for the new version of the script - much improved over this version in many ways.

Dale · http://www.creative-dreaming.com
#141 · Thursday August 27, 2009

Hi,

Firstly great job… its is a really excellent piece of work.

Two questions,

1) Is there any way to clear the date, I tend to make the input field read only and force the user to use the date-picker but then they need to be able to clear their selection for fields that are not compulsory.

2) How do you suggest dealing with a date-of-birth field, it can take quite some clicks to click back to the year of birth. I have seen some date-pickers that allow once to select the year from a dropdown list but thats not always that nice. Just curious really.

Cheers

omar
#142 · Saturday August 29, 2009

NICE DATE PICKER

but I’d like to second the recent comment about dropping the necessary folder/files and putting the html code only to find there’s no calender icon to click on!

can you please keep it simple and give us a working example of how to put up a simple picker i.e only necessary files and working html code.

a good way would be to have just one date picker on a page and we can just copy the html. If we need the more customization options, we can look deeper into the options but for now I can’t even put a basic datepicker after putting the js,css,media folder and basic html line:

<input type=“text” id=“anID” name=“dt” class=“dateformat-d-sl-m-sl-Y value=”“ />

i.e please keep it simple to add it to out web page.

thanks,
omar

Kristoffer Ahl · http://www.spinit.se
#143 · Tuesday September 1, 2009

Thanks for your great work with the datepicker! I’ve used it on several projects and have been really happy with it!
However, on the current project I’m using the inline datepicker and I’m experiencing a bug in IE 6, 7, 8 and FF 3.5 (haven’t tried any others).

When a date has been selected, clicking the next month button will step 2 months instead of just 1. When you try to step back 1 month it will step back 2 months. I can’t seem to reproduce the error with all dates but for some reason, selecting the 2nd of November 2009 seems to trigger it (I tried it on your demopage).

The bug (or at least a similar one) seems to have been mentioned before by MarkB (#128 · Tuesday July 21, 2009) and igor (#56 · Tuesday March 17, 2009). I was just wondering where you are on fixing this issue and if you are planning a release that will fix this bug?

Once again, many thanks for your great work!
/ Kristoffer

Update by f.d: Hi Kristoffer, the bug has been fixed in the new v5 release... I just have to go and write the accompanying article!

Leo
#144 · Tuesday September 1, 2009

Is there a method to dynamically disable days of the week? For instance, all Thursdays.

Klaus · http://white-island.org
#145 · Tuesday September 8, 2009

Thank you guy for this amazing datepicker ! I’m using it with Joomla, within a form framework called “BreezingForms”, the sucessor of “FacileForms”, for Joomla 1.5. As good as it gets for forms in Joomla. Its on here :
http://east-end-apartment.de/de/buchung/
The localisation is setup working for the browser language, as far as I understand it, however I would like to bind it to the content language of the page. Should be easy, but the method concerning the language is already beyond my scope of javascript. Sure you could, but would you show me howto do zhat ?
Greetings from Ibiza!

Update by f.d: Hi Klaus, the new version does exactly that and tests the language of the page before testing the browsers current language.

So, if you set a lang="de" attribute on the HTML node, then the script will attempt to load the "de.js" language file. If no language can be parsed from the HTML node's lang attribute, the script then tests the browser language.

P.S: Haven't been in Ibiza in years! Lovely Island indeed...

Klaus
#146 · Tuesday September 8, 2009

Thanks, great synchronicity… I just got the v5 script from your demo page and put it where v4 was, but its not working. Waiting patiently for the release-

Ankur Sharmaa · http://www.test.com
#147 · Friday September 11, 2009

Your date picker calender are very good ….i think best…..But to present the way of code of all these are very poor or beter say bad…… please if want to help freshers, so make it simple . and step by step….Now your solution dificult to understand at once. . please dont take otherwise ….
It is only an advice.

Regards.

Crosslink
#148 · Friday September 11, 2009

Is it possible to disable previous days ?
Thank you

Web Design Company · http://www.goweb99.com
#149 · Sunday September 13, 2009

great work… thanks

Comments are currently closed for this article but feel free to email me with your input - I’d love to hear it.

Popular Frequencies

  • Unobtrusive Table Sort Script (revi…
    Saturday September 16, 2006
  • Unobtrusive Date-Picker Widget Upda…
    Monday October 02, 2006
  • Unobtrusive Date-Picker Widget V4
    Tuesday February 03, 2009
  • Unobtrusive Table Sort Script
    Friday November 18, 2005
  • Unobtrusive Date-Picker Widget V5
    Wednesday September 09, 2009
All articles