• Stars
    star
    2,913
  • Rank 14,894 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

📆 Customizable date (and time) picker. Opt-in UI, no jQuery!

rome

Customizable date (and time) picker. Opt-in UI, no jQuery!

Rome wasn't built in a day. Browser support includes every sane browser and IE7+.

Demo!

You can see a live demo here.

screenshot.png

Oh, rome synchronizes in real-time with inputs, never steals focus, and its CSS is entirely customizable!

Rome depends on moment. It doesn't depend on jQuery or other weird frameworks, though.

Install

From npm or Bower.

npm install --save @bevacqua/rome
bower install --save @bevacqua/rome

Note that if you're using the standalone version, the API is published under the rome global. If you're using CJS, then you'll have to require('@bevacqua/rome').

Setup

You can use your own distribution of moment, using rome.standalone.js.

<script src='moment.js'></script>
<script src='rome.standalone.js'></script>

You could just use the bundled rome.js distribution, which comes with moment in it.

<script src='rome.js'></script>

If you need to do anything regarding internationalization, refer to moment for that. Ideally, make those changes before starting to create Rome calendar components.

API

The API in rome exposes a few properties.

rome.find(elem)

If a calendar is associated to the provided elem, then that calendar is returned, otherwise returns null. DOM elements can only have one associated calendar.

rome(elem, options={})

This method creates a calendar instance and associates it to the provided elem. This association can't be undone even by .destroy()ing the rome instance, because it can be .restore()d later. Subsequent calls to rome(elem) will return the associated calendar, instead of creating a new one (see rome.find(elem)). Think of this as a "caching feature".

Creating a calendar has a ton of options. These have reasonable defaults that are easy to adjust, too. The options are listed below.

Option Description
appendTo DOM element where the calendar will be appended to. Takes 'parent' as the parent element
autoClose When set to true, the calendar is auto-closed when picking a day _(or a time if time: true and date: false). A value of 'time' will only auto-close the calendar when a time is picked.
autoHideOnBlur Hides the calendar when focusing something other than the input field
autoHideOnClick Hides the calendar when clicking away
date The calendar shows days and allows you to navigate between months
dateValidator Function to validate that a given date is considered valid. Receives a native Date parameter.
dayFormat Format string used to display days on the calendar
initialValue Value used to initialize calendar. Takes string, Date, or moment
inputFormat Format string used for the input field as well as the results of rome
invalidate Ensures the date is valid when the field is blurred
strictParse Compares input strictly against inputFormat, and partial matches are discarded
max Disallow dates past max. Takes string, Date, or moment
min Disallow dates before min. Takes string, Date, or moment
monthFormat Format string used by the calendar to display months and their year
monthsInCalendar How many months get rendered in the calendar
required Is the field required or do you allow empty values?
styles CSS classes applied to elements on the calendar
time The calendar shows the current time and allows you to change it using a dropdown
timeFormat Format string used to display the time on the calendar
timeInterval Seconds between each option in the time dropdown
timeValidator Function to validate that a given time is considered valid. Receives a native Date parameter.
weekdayFormat Format used to display weekdays. Takes min (Mo), short (Mon), long (Monday), or an array with seven strings of your choosing.
weekStart Day considered the first of the week. Range: Sunday 0 - Saturday 6

Note that in the case of input fields, when initialValue isn't provided the initial value is inferred from elem.value instead. In the case of inline calendars, new Date() will be used as a default if none is provided.

Inlining the Calendar

If you pass in an element other than an input tag, then this method behaves slightly differently. The difference is that appendTo becomes the provided elem, and the calendar won't attach itself to an input element. The options listed below will be ignored.

  • autoHideOnBlur, because there is no input field that can be tracked for blur events
  • invalidate, because there is no input field to keep consistent with the calendar component
  • required, because you can easily do that on an input field
  • styles.positioned, because the calendar will be considered inlined

All of the other options still apply, and identical behavior should be expected.

Default Options

If you don't set an option, the default will be used. You can look up the defaults here, or below.

{
  "appendTo": document.body,
  "autoClose": true,
  "autoHideOnBlur": true,
  "autoHideOnClick": true,
  "date": true,
  "dateValidator": Function.prototype,
  "dayFormat": "DD",
  "initialValue": null,
  "inputFormat": "YYYY-MM-DD HH:mm",
  "invalidate": true,
  "max": null,
  "min": null,
  "monthFormat": "MMMM YYYY",
  "monthsInCalendar": 1,
  "required": false,
  "strictParse": false,
  "styles": {
    "back": "rd-back",
    "container": "rd-container",
    "date": "rd-date",
    "dayBody": "rd-days-body",
    "dayBodyElem": "rd-day-body",
    "dayConcealed": "rd-day-concealed",
    "dayDisabled": "rd-day-disabled",
    "dayHead": "rd-days-head",
    "dayHeadElem": "rd-day-head",
    "dayRow": "rd-days-row",
    "dayTable": "rd-days",
    "month": "rd-month",
    "next": "rd-next",
    "positioned": "rd-container-attachment",
    "selectedDay": "rd-day-selected",
    "selectedTime": "rd-time-selected",
    "time": "rd-time",
    "timeList": "rd-time-list",
    "timeOption": "rd-time-option"
  },
  "time": true,
  "timeFormat": "HH:mm",
  "timeInterval": 1800,
  "timeValidator": Function.prototype,
  "weekdayFormat": "min",
  "weekStart": moment().weekday(0).day()
}

Rome API

When you create a calendar with rome(elem), you'll get a cal instance back. This has a few API methods. Most of these methods return the calendar instance whenever possible, allowing for method chaining.

.show()

Shows the calendar. If associated with an input, the calendar gets absolutely position right below the input field.

.hide()

Hides the calendar.

.id

Auto-generated unique identifier assigned to this instance of Rome.

.container

The DOM element that contains the calendar.

.associated

The associated DOM element assigned to this calendar instance. This is the input field or parent element that you used to create the calendar.

.getDate()

Returns the current date, as defined by the calendar, in a native Date object. If required: false you'll get null when the input field is empty.

.getDateString(format?)

Returns the current date, as defined by the calendar, using the provided options.inputFormat format string or a format of your choosing. If required: false you'll get null when the input field is empty.

.getMoment()

Returns a copy of the moment object underlying the current date in the calendar. If required: false you'll get null when the input field is empty.

.destroy()

Removes the calendar from the DOM and all of its associated DOM event listeners. The only responsive API method becomes the .restore method described below, the rest of the API becomes no-op methods. After emitting the destroyed event, all event listeners are removed from the instance.

.destroyed

Returns true when the calendar is in a destroyed state and false otherwise.

.restore(options?)

Restores the calendar, using the provided options (or the default options). The associated DOM element can't be changed. The API methods are restored to their original functionality.

.options(options?)

If an options object is provided, it destroys the calendar and initializes it with the provided options. Effectively the same as calling .restore(options) immediately after calling .destroy().

If no options object is provided, a copy of the current options is returned.

.options.reset()

Resets the options to the factory defaults. Effectively the same as calling .options({}) while preserving the appendTo option.

.emitValues()

Emits all of the data events listed below. Mostly used internally, should be avoided in consumer-land.

.setValue(value)

Sets the current date to the provided value, but only if that value is valid according to the rules defined by the calendar. Takes string, Date, or moment. Mostly used internally, and it doesn't emit any events.

.refresh()

Forces a refresh of the calendar. This method will redraw the month and update the dates that can be selected in accordance with dateValidator and timeValidator.

.back()

Steps the calendar display back by one month. Equivalent to clicking the 'back' button. Returns undefined.

.next()

Steps the calendar display forward by one month. Equivalent to clicking the 'next' button. Returns undefined.

Events

Rome calendars also provide a few events you can subscribe to. These events are published through an event emitter created using contra. These events are listed below.

Event Arguments Description
ready [options] The calendar has been .restored
destroyed [] The calendar has been .destroyed
data [value] The date may have been updated by the calendar. Value of .getDateString() is provided
year [year] The year may have been updated by the calendar. Value of moment.year() is provided
month [month] The month may have been updated by the calendar. Value of moment.month() is provided
day [day] The day may have been updated by the calendar. Value of moment.date() is provided
time [time] The time may have been updated by the calendar. Formatted time string is provided
show [] The calendar has been displayed
hide [] The calendar has been hidden
back [month] The calendar view has been moved back a month to the value moment.month()
next [month] The calendar view has been moved forward a month to the value moment.month()

Date and Time Validator

Please note that dateValidator and timeValidator both receive a native Date object as a parameter. These methods are expected to return undefined or true if the date is deemed valid, and false in case the date is invalid. If dateValidator returns false, the validation process will try to find a valid date near the desired date.

If dateValidator passes for a given date, the timeValidator will attempt to validate that date as well. If the time is invalid, the day will be probed for a valid time. This validation starts at the desired time, and grows in timeInterval increments. When the end of the day is reached, validation resumes at the start of the day instead of leaping to the next day.

rome.val

There are a few default validator factories provided by Rome to make your life easier.

These methods take a moment, a Date, a string that can be parsed into a moment using inputFormat, or a DOM element that Rome could use to look up another Rome instance.

If you passed in a DOM element, the validator will look up the associated Rome instance and validate using its value. The first time the validator is executed on any inline calendar, the 'data' event for that calendar will be hooked to refresh the related calendar.

For usage examples you can refer to the demos.

rome.val.afterEq(value)

Returns whether the date is after the provided value. The comparison uses >=, meaning it's inclusive.

rome.val.after(value)

Returns whether the date is after the provided value. The comparison uses >, meaning it's exclusive.

rome.val.beforeEq(value)

Returns whether the date is before the provided value. The comparison uses <=, meaning it's inclusive.

rome.val.before(value)

Returns whether the date is before the provided value. The comparison uses <, meaning it's exclusive.

rome.val.except(left, right)

Returns whether the date is any date except the provided value. You can provide a wide variety of input values. Keep in mind Date, string, moment, and the DOM element used to find another calendar are all valid input types.

Providing left only means "any date except this one"

If you use rome.val.except('2014-08-09'), then '2014-08-09' is invalid.

Providing left and right means "any date that's not in this range"

If you use rome.val.except('2014-08-09', '2014-09-01'), then anything between '2014-08-09' and '2014-09-01' is invalid.

If left is an array, each element in the array is treated as the simple case described above

In this case, right is completely ignored. Every item in the array is treated as follows.

If the item is single, then a rule is built on that single date

Using rome.val.except(['2014-08-09', '2014-09-01']) means that '2014-08-09' and '2014-09-01' are both invalid dates.

If the item is an array, the first two items are used to determine a date range

Using rome.val.except([['2014-08-09', '2014-09-01']]) means anything between '2014-08-09' and '2014-09-01' is invalid.

These two types of entries can be combined in any way you like. Each entry will exclude additional dates.

For instance, [['2014-04-05', '2014-04-15'], ['2014-04-25', '2014-04-30'], '2014-05-05'] means that April 05 to 15, and April 25 to 30, along with May 05 are all invalid dates.

rome.val.only(left, right)

Identical behavior to rome.val.except, except for the fact that the selected dates become the only valid dates, rather than the only invalid dates.

rome.moment

Exposes the moment instance used by Rome. To change the moment instance, refer to rome.use(moment).

rome.use(moment)

Sets the instance of moment used by Rome.

Development

Start by installing any dependencies.

npm install

Then run the Gulp watch task.

gulp watch

Lastly open the page and any changes you make just need a browser refresh.

open index.html

License

MIT

More Repositories

1

dragula

👌 Drag and drop so simple it hurts
JavaScript
21,766
star
2

es6

🌟 ES6 Overview in 350 Bullet Points
4,328
star
3

js

🎨 A JavaScript Quality Guide
2,874
star
4

fuzzysearch

🔮 Tiny and blazing-fast fuzzy search in JavaScript
JavaScript
2,698
star
5

woofmark

🐕 Barking up the DOM tree. A modular, progressive, and beautiful Markdown and HTML editor
JavaScript
1,616
star
6

promisees

📨 Promise visualization playground for the adventurous
JavaScript
1,202
star
7

horsey

🐴 Progressive and customizable autocomplete component
JavaScript
1,163
star
8

css

🎨 CSS: The Good Parts
992
star
9

react-dragula

👌 Drag and drop so simple it hurts
JavaScript
990
star
10

contra

🏄 Asynchronous flow control with a functional taste to it
JavaScript
771
star
11

shots

🔫 pull down the entire Internet into a single animated gif.
JavaScript
725
star
12

insignia

🔖 Customizable tag input. Progressive. No non-sense!
JavaScript
673
star
13

campaign

💌 Compose responsive email templates easily, fill them with models, and send them out.
JavaScript
641
star
14

perfschool

🌊 Navigate the #perfmatters salt marsh waters in this NodeSchool workshopper
CSS
629
star
15

local-storage

🛅 A simplified localStorage API that just works
JavaScript
522
star
16

angularjs-dragula

👌 Drag and drop so simple it hurts
HTML
510
star
17

reads

📚 A list of physical books I own and read
486
star
18

insane

😾 Lean and configurable whitelist-oriented HTML sanitizer
JavaScript
438
star
19

hget

👏 Render websites in plain text from your terminal
HTML
334
star
20

hit-that

✊ Render beautiful pixel perfect representations of websites in your terminal
JavaScript
331
star
21

swivel

Message passing between ServiceWorker and pages made simple
JavaScript
293
star
22

hash-sum

🎊 Blazing fast unique hash generator
JavaScript
292
star
23

dominus

💉 Lean DOM Manipulation
JavaScript
277
star
24

trunc-html

📐 truncate html by text length
JavaScript
220
star
25

grunt-ec2

📦 Create, deploy to, and shutdown Amazon EC2 instances
JavaScript
190
star
26

beautify-text

✒️ Automated typographic quotation and punctuation marks
JavaScript
185
star
27

sixflix

🎬 Detects whether a host environment supports ES6. Algorithm by Netflix.
JavaScript
174
star
28

twitter-for-github

🐥 Twitter handles for GitHub
JavaScript
146
star
29

awesome-badges

🏆 Awesome, badges!
JavaScript
124
star
30

prop-tc39

Scraping microservice for TC39 proposals 😸
JavaScript
107
star
31

megamark

😻 Markdown with easy tokenization, a fast highlighter, and a lean HTML sanitizer
JavaScript
102
star
32

diferente

User-friendly virtual DOM diffing
JavaScript
95
star
33

domador

😼 Dependency-free and lean DOM parser that outputs Markdown
JavaScript
83
star
34

proposal-undefined-coalescing-operator

Undefined Coalescing Operator proposal for ECMAScript
76
star
35

dotfiles

💠 Yay! @bevacqua does dotfiles \o/
Shell
75
star
36

assignment

😿 Assign property objects onto other objects, recursively
JavaScript
73
star
37

sektor

📍 A slim alternative to jQuery's Sizzle
JavaScript
65
star
38

map-tag

🏷 Map template literal expression interpolations with ease.
JavaScript
65
star
39

unbox

Unbox a node application with a well-designed build-oriented approach in minutes
JavaScript
61
star
40

hint

Awesome tooltips at your fingertips
JavaScript
60
star
41

but

🛰 But expands your functional horizons to the edge of the universe
JavaScript
59
star
42

kanye

Smash your keyboards with ease
JavaScript
55
star
43

correcthorse

See XKCD for reference
JavaScript
52
star
44

easymap

🗺 simplified use of Google Maps API to render a bunch of markers.
JavaScript
52
star
45

flickr-cats

A demo page using the Flickr API, ServiceWorker, and plain JavaScript
HTML
49
star
46

ruta3

Route matcher devised for shared rendering JavaScript applications
JavaScript
46
star
47

poser

📯 Create clean arrays, or anything else, which you can safely extend
JavaScript
45
star
48

hubby

👨 Hubby is a lowly attempt to describe public GitHub activity in natural language
JavaScript
45
star
49

baal

🐳 Automated, autoscaled, zero-downtime, immutable deployments using plain old bash, Packer, nginx, Node.js, and AWS. Made easy.
Shell
44
star
50

lipstick

💄 sticky sessions for Node.js clustering done responsibly
JavaScript
43
star
51

crossvent

🌏 Cross-platform browser event handling
JavaScript
41
star
52

lazyjs

The minimalist JavaScript loader
JavaScript
39
star
53

spritesmith-cli

😳 Adds a CLI to the spritesmith module
JavaScript
38
star
54

gulp-jsfuck

Fuck JavaScript and obfuscate it using only 6 characters ()+[]!
JavaScript
37
star
55

measly

A measly wrapper around XHR to help you contain your requests
JavaScript
36
star
56

keynote-extractor

🎁 Extract Keynote presentations to JSON and Markdown using a simple script.
AppleScript
35
star
57

hyperterm-working-directory

🖥👷📂 Adds a default working directory setting. Opens new tabs using that working directory.
JavaScript
34
star
58

gitcanvas

🏛 Use your GitHub account's commit history as a canvas. Express the artist in you!
JavaScript
34
star
59

cave

Remove critical CSS from your stylesheet after inlining it in your pages
JavaScript
33
star
60

scrape-metadata

📜 HTML metadata scraper
JavaScript
31
star
61

feeds

🍎 RSS feeds I follow and maintain
31
star
62

suchjs

Provides essential jQuery-like methods for your evergreen browser, in under 200 lines of code. Such small.
JavaScript
30
star
63

ponyedit

An interface between contentEditable and your UI
JavaScript
29
star
64

grunt-grunt

Spawn Grunt tasks in other Gruntfiles easily from a Grunt task
JavaScript
29
star
65

ultramarked

Marked with built-in syntax highlighting and input sanitizing that doesn't encode all HTML.
JavaScript
28
star
66

sell

💰 Cross-browser text input selection made simple
JavaScript
28
star
67

icons

Free icon sets gathered around the open web
27
star
68

insert-rule

Insert rules into a stylesheet programatically with a simple API
JavaScript
26
star
69

hose

Redirect any domain to localhost for convenience or productivity!
JavaScript
26
star
70

ponymark

Next-generation PageDown fork
JavaScript
25
star
71

omnibox

Fast url parsing with a tiny footprint and extensive browser support
JavaScript
25
star
72

estimate

Calculate remaining reading time estimates in real-time
JavaScript
24
star
73

seleccion

💵 A getSelection polyfill and a setSelection ranch dressing
JavaScript
24
star
74

node-emoji-random

Creates a random emoji string. This is as useless as it gets.
JavaScript
24
star
75

bullseye

🎯 Attach elements onto their target
JavaScript
23
star
76

vectorcam

🎥 Record gifs out of <svg> elements painlessly
JavaScript
22
star
77

paqui

Dead simple, packager-agnostic package management solution for front-end component developers
JavaScript
22
star
78

sluggish

🐍 Sluggish slug generator that works universally
JavaScript
22
star
79

grunt-ngdoc

Grunt task for generating documentation using AngularJS' @ngdoc comments
JavaScript
20
star
80

ftco

⚡ Browser extension that unshortens t.co links in TweetDeck and Twitter
JavaScript
19
star
81

jadum

💍 A lean Jade compiler that understands Browserify and reuses partials
JavaScript
19
star
82

trunc-text

📏 truncate text by length, doesn't cut words
JavaScript
16
star
83

flexarea

Pretty flexible areas!
JavaScript
16
star
84

music-manager

📻 Manages a list of favorite artists and opens playlists on youtube.
JavaScript
16
star
85

grunt-integration

Run Integration Tests using Selenium, Mocha, a Server, and a Browser
JavaScript
15
star
86

apartment

🏡 Remove undesirable properties from a piece of css
JavaScript
14
star
87

mongotape

Run integration tests using mongoose and tape
JavaScript
14
star
88

rehearsal

Persist standard input to a file, then simulate real-time program execution.
JavaScript
13
star
89

queso

Turn a plain object into a query string
JavaScript
13
star
90

bitfin

🏦 Finance utility for Bitstamp
JavaScript
13
star
91

grunt-spriting-example

An example on how to seamlessly use spritesheets with Grunt.
12
star
92

pandora-box

🐼 What will it be?
JavaScript
12
star
93

artists

🎤 Big list of artists pulled from Wikipedia.
JavaScript
11
star
94

reaver

Minimal asset hashing CLI and API
JavaScript
11
star
95

atoa

Creates a true array based on `arraylike`, starting at `startIndex`.
JavaScript
10
star
96

twitter-leads

🐦 Pull list of leads from a Twitter Ads Lead Generation Card
JavaScript
10
star
97

BridgeStack

.NET StackExchange API v2.0 client library wrapper
C#
10
star
98

ama

📖 A repository to ask @bevacqua anything.
10
star
99

virtual-host

Create virtual, self-contained `connect` or `express` applications using a very simple API.
JavaScript
10
star
100

banksy

🌇 Street art between woofmark and horsey
JavaScript
10
star