Coder Social home page Coder Social logo

datepicker's Introduction

 ____             __                               __
/\  _`\          /\ \__                 __        /\ \
\ \ \/\ \     __ \ \ ,_\    __   _____ /\_\    ___\ \ \/'\      __   _ __
 \ \ \ \ \  /'__`\\ \ \/  /'__`\/\ '__`\/\ \  /'___\ \ , <    /'__`\/\`'__\
  \ \ \_\ \/\ \L\.\\ \ \_/\  __/\ \ \L\ \ \ \/\ \__/\ \ \\`\ /\  __/\ \ \/
   \ \____/\ \__/.\_\ \__\ \____\\ \ ,__/\ \_\ \____\\ \_\ \_\ \____\\ \_\
    \/___/  \/__/\/_/\/__/\/____/ \ \ \/  \/_/\/____/ \/_/\/_/\/____/ \/_/
                                   \ \_\
                                    \/_/ By: The Qodesmith

Datepicker.js · npm version

Get a date with JavaScript! Or a daterange, but that's not a good pun. Datepicker has no dependencies and weighs in at 5.9kb gzipped! Datepicker is simple to use and looks sexy on the screen. A calendar pops up and you pick a date. #Boom.

Datepicker screenshot

Table of Contents

Event Callbacks

Customizations

Settings

Disabling Things

ID - Daterange

Instance Methods

See the examples below.

Installation

Manually

Simply include datepicker.min.css in the <head>...

<head>
  ...
  <link rel="stylesheet" href="datepicker.min.css">
  <!-- Or remotely via Unpkg CDN -->
  <!-- <link rel="stylesheet" href="https://unpkg.com/js-datepicker/dist/datepicker.min.css"> -->
</head>

and include datepicker.min.js just above your closing </body> tag...

<body>
  ...
  <script src="datepicker.min.js"></script>
  <!-- Or remotely via Unpkg CDN -->
  <!-- <script src="https://unpkg.com/js-datepicker"></script> -->
</body>

If you downloaded the package via zip file from Github, these files are located in the dist folder. Otherwise, you can use the Unpkg CDN as shown in the examples above.

Via NPM

npm install js-datepicker

Files & locations:

File Folder Description
datepicker.min.js node_modules/js-datepicker/dist production build - (ES5, 5.9kb gzipped)
datepicker.min.css node_modules/js-datepicker/dist production stylesheet
datepicker.scss node_modules/js-datepicker/src Scss file. Use it in your own builds.

Basic Usage

Importing the library if you're using it in Node:

import datepicker from 'js-datepicker'
// or
const datepicker = require('js-datepicker')

Using it in your code:

const picker = datepicker(selector, options)

Importing the styles into your project using Node:

// From within a scss file,
// import datepickers scss file...
@import '~js-datepicker/src/datepicker';

// or import datepickers css file.
@import '~js-datepicker/dist/datepicker.min.css';

Datepicker takes 2 arguments:

  1. selector - two possibilities:
    1. string - a CSS selector, such as '.my-class', '#my-id', or 'div'.
    2. DOM node - provide a DOM node, such as document.querySelector('#my-id').
  2. (optional) An object full of options.

The return value of the datepicker function is the datepicker instance. See the methods and properties below.

You can use Datepicker with any type of element you want. If used with an <input> element (the common use case), then the <input>'s value will automatically be set when selecting a date.

NOTE: Datepicker will not change the value of input fields with a type of date - <input type="date">. This is because those input's already have a built in calendar and can cause problems. Use <input type="text"> instead.

Manual Year & Month Navigation

By clicking on the year or month an overlay will show revealing an input field and a list of months. You can either enter a year in the input, click a month, or both:

Datepicker screenshot

Using As A Daterange Picker

Want 2 calendars linked together to form Voltron a daterange picker? It's as simple as giving them both the same id! By using the id option, Datepicker handles all the logic to keep both calendars in sync.

Datepicker daterange screenshot

The 1st calendar will serve as the minimum date and the 2nd calendar as the maximum. Dates will be enabled / disabled on each calendar automatically when the user selects a date on either. The getRange method will conveniently give you an object with the start and end date selections. It's as simple as creating 2 instances with the same id to form a daterange picker:

const start = datepicker('.start', { id: 1 })
const end = datepicker('.end', { id: 1 })

And when you want to get your start and end values, simply call getRange on either instance:

start.getRange() // { start: <JS date object>, end: <JS date object> }
end.getRange() // Gives you the same as above!

Custom Elements / Shadow DOM Usage

You can use Datepicker within a Shadow DOM and custom elements. In order to do so, must pass a node as the 1st argument:

class MyElement extends HTMLElement {
  constructor() {
    super()
    const shadowRoot = this.attachShadow({ mode: 'open' })
    shadowRoot.innerHTML = `
      <div>
        <style>${textOfDatepickersCSS}</style>
        <input />
      </div>
    `

    // Create the node we'll pass to datepicker.
    this.input = shadowRoot.querySelector('input')
  }

  connectedCallback() {
    // Pass datepicker a node within the shadow DOM.
    datepicker(this.input)
  }
}

customElements.define('my-element', MyElement)

All other options work as expected, including dateranges. You can even have a date range pair with one calendar in the shadow DOM and another outside it!


Options - Event Callbacks

Use these options if you want to fire off your own functions after something happens with the calendar.

onSelect

Callback function after a date has been selected. The 2nd argument is the selected date when a date is being selected and undefined when a date is being unselected. You unselect a date by clicking it again.

const picker = datepicker('.some-input', {
  onSelect: (instance, date) => {
    // Do stuff when a date is selected (or unselected) on the calendar.
    // You have access to the datepicker instance for convenience.
  }
})
  • Arguments:
    1. instance - the current datepicker instance.
    2. date:
      • JavaScript date object when a date is being selected.
      • undefined when a date is being unselected.

NOTE: This will not fire when using the instance methods to manually change the calendar.

onShow

Callback function when the calendar is shown.

const picker = datepicker('.some-input', {
  onShow: instance => {
    // Do stuff when the calendar is shown.
    // You have access to the datepicker instance for convenience.
  }
})
  • Arguments:
    1. instance - the current datepicker instance.

NOTE: This will fire when using the show instance method.

onHide

Callback function when the calendar is hidden.

const picker = datepicker('.some-input', {
  onHide: instance => {
    // Do stuff once the calendar goes away.
    // You have access to the datepicker instance for convenience.
  }
})
  • Arguments:
    1. instance - the current datepicker instance.

NOTE: This will fire when using the hide instance method.

onMonthChange

Callback function when the month has changed.

const picker = datepicker('.some-input', {
  onMonthChange: instance => {
    // Do stuff when the month changes.
    // You have access to the datepicker instance for convenience.
  }
})
  • Arguments:
    1. instance - the current datepicker instance.

Options - Customizations

These options help you customize the calendar to your suit your needs. Some of these are especially helpful if you're using a language other than English.

formatter

Using an input field with your datepicker? Want to customize its value anytime a date is selected? Provide a function that manually sets the provided input's value with your own formatting.

const picker = datepicker('.some-input', {
  formatter: (input, date, instance) => {
    const value = date.toLocaleDateString()
    input.value = value // => '1/1/2099'
  }
})
  • Default - default format is date.toDateString()
  • Arguments:
    1. input - the input field that the datepicker is associated with.
    2. date - a JavaScript date object of the currently selected date.
    3. instance - the current datepicker instance.

Note: The formatter function will only run if the datepicker instance is associated with an <input> field.

position

This option positions the calendar relative to the <input> field it's associated with. This can be 1 of 5 values: 'tr', 'tl', 'br', 'bl', 'c' representing top-right, top-left, bottom-right, bottom-left, and centered respectively. Datepicker will position itself accordingly relative to the element you reference in the 1st argument. For a value of 'c', Datepicker will position itself fixed, smack in the middle of the screen. This can be desirable for mobile devices.

// The calendar will be positioned to the top-left of the input field.
const picker = datepicker('.some-input', { position: 'tl' })
  • Type - string
  • Default - 'bl'

startDay

Specify the day of the week your calendar starts on. 0 = Sunday, 1 = Monday, etc. Plays nice with the customDays option.

// The first day of the week on this calendar is Monday.
const picker = datepicker('.some-input', { startDay: 1 })
  • Type - number (0 - 6)
  • Default - 0 (Sunday starts the week)

customDays

You can customize the display of days on the calendar by providing an array of 7 values. This can be used with the startDay option if your week starts on a day other than Sunday.

const picker = datepicker('.some-input', {
  customDays: ['天', '一', '二', '三', '四', '五', '六']
})

Custom days screenshot

  • Type - array
  • Default - ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']

customMonths

You can customize the display of the month name at the top of the calendar by providing an array of 12 strings.

const picker = datepicker('.some-input', {
  customMonths: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre']
})

Custom months screenshot

  • Type - array
  • Default - ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

customOverlayMonths

You can customize the display of the month names in the overlay view by providing an array of 12 strings. Keep in mind that if the values are too long, it could produce undesired results in the UI.

Here's what the default looks like:

Custom overlay months default screenshot

Here's an example with an array of custom values:

const picker = datepicker('.some-input', {
  customOverlayMonths: ['😀', '😂', '😎', '😍', '🤩', '😜', '😬', '😳', '🤪', '🤓 ', '😝', '😮']
})

Custom overlay months screenshot

  • Type - array
  • Default - The first 3 characters of each item in customMonths.

defaultView

Want the overlay to be the default view when opening the calendar? This property is for you. Simply set this property to 'overlay' and you're done. This is helpful if you want a month picker to be front and center.

const picker = datepicker('.some-input', {defaultView: 'overlay'})
  • Type - string ('calendar' or 'overlay')
  • Default - 'calendar'

overlayButton

Custom text for the year overlay submit button.

const picker = datepicker('.some-input', {
  overlayButton: "¡Vamanos!"
})

Custom overlay text screenshot

  • Type - string
  • Default - 'Submit'

overlayPlaceholder

Custom placeholder text for the year overlay.

const picker = datepicker('.some-input', {
  overlayPlaceholder: 'Entrar un año'
})

Custom overlay placeholder screenshot

  • Type - string
  • Default - '4-digit year'

events

An array of dates which indicate something is happening - a meeting, birthday, etc. I.e. an event.

const picker = datepicker('.some-input', {
  events: [
    new Date(2019, 10, 1),
    new Date(2019, 10, 10),
    new Date(2019, 10, 20),
  ]
})

Events on calendar screenshot

  • Type - array of JS date objects

Options - Settings

Use these options to set the calendar the way you want.

alwaysShow

By default, the datepicker will hide & show itself automatically depending on where you click or focus on the page. If you want the calendar to always be on the screen, use this option.

const picker = datepicker('.some-input', { alwaysShow: true })
  • Type - boolean
  • Default - false

dateSelected

This will start the calendar with a date already selected. If Datepicker is used with an <input> element, that field will be populated with this date as well.

const picker = datepicker('.some-input', { dateSelected: new Date(2099, 0, 5) })
  • Type - JS date object

maxDate

This will be the maximum threshold of selectable dates. Anything after it will be unselectable.

const picker = datepicker('.some-input', { maxDate: new Date(2099, 0, 1) })
  • Type - JavaScript date object.

NOTE: When using a daterange pair, if you set maxDate on the first instance options it will be ignored on the 2nd instance options.

minDate

This will be the minumum threshold of selectable dates. Anything prior will be unselectable.

const picker = datepicker('.some-input', { minDate: new Date(2018, 0, 1) })
  • Type - JavaScript date object.

NOTE: When using a daterange pair, if you set minDate on the first instance options it will be ignored on the 2nd instance options.

startDate

The date you provide will determine the month that the calendar starts off at.

const picker = datepicker('.some-input', { startDate: new Date(2099, 0, 1) })
  • Type - JavaScript date object.
  • Default - today's month

showAllDates

By default, the datepicker will not put date numbers on calendar days that fall outside the current month. They will be empty squares. Sometimes you want to see those preceding and trailing days. This is the option for you.

const picker = datepicker('.some-input', { showAllDates: true })

Show all dates on screenshot

  • Type - boolean
  • Default - false

respectDisabledReadOnly

<input />'s can have a disabled or readonly attribute applied to them. In those cases, you might want to prevent Datepicker from selecting a date and changing the input's value. Set this option to true if that's the case. The calendar will still be functional in that you can change months and enter a year, but dates will not be selectable (or deselectable).

const picker = datepicker('.some-input', { respectDisabledReadOnly: true })
  • Type - boolean
  • Default - false

Options - Disabling Things

These options are associated with disabled various things.

noWeekends

Provide true to disable selecting weekends. Weekends are Saturday & Sunday. If your weekends are a set of different days or you need more control over disabled dates, check out the disabler option.

const picker = datepicker('.some-input', { noWeekends: true })
  • Type - boolean
  • Default - false

disabler

Sometimes you need more control over which dates to disable. The disabledDates option is limited to an explicit array of dates and the noWeekends option is limited to Saturdays & Sundays. Provide a function that takes a JavaScript date as it's only argument and returns true if the date should be disabled. When the calendar builds, each date will be run through this function to determine whether or not it should be disabled.

const picker1 = datepicker('.some-input1', {
  // Disable every Tuesday on the calendar (for any given month).
  disabler: date => date.getDay() === 2
})

const picker2 = datepicker('.some-input2', {
  // Disable every day in the month of October (for any given year).
  disabler: date => date.getMonth() === 9
})
  • Arguments:
    1. date - JavaScript date object representing a given day on a calendar.

disabledDates

Provide an array of JS date objects that will be disabled on the calendar. This array cannot include the same date as dateSelected. If you need more control over which dates are disabled, see the disabler option.

const picker = datepicker('.some-input', {
  disabledDates: [
    new Date(2099, 0, 5),
    new Date(2099, 0, 6),
    new Date(2099, 0, 7),
  ]
})
  • Type - array of JS date objects

disableMobile

Optionally disable Datepicker on mobile devices. This is handy if you'd like to trigger the mobile device's native date picker instead. If that's the case, make sure to use an input with a type of "date" - <input type="date" />

const picker = datepicker('.some-input', { disableMobile: true })
  • Type - boolean
  • Default - false

disableYearOverlay

Clicking the year or month name on the calendar triggers an overlay to show, allowing you to enter a year manually. If you want to disable this feature, set this option to true.

const picker = datepicker('.some-input', { disableYearOverlay: true })
  • Type - boolean
  • Default - false

disabled

Want to completely disable the calendar? Simply set the disabled property on the datepicker instance to true to render it impotent. Maybe you don't want the calendar to show in a given situation. Maybe the calendar is showing but you don't want it to do anything until some other field is filled out in a form. Either way, have fun.

Example:

const picker = datepicker('.some-input')

function disablePicker() {
  picker.disabled = true
}

function enablePicker() {
  picker.disabled = false
}

function togglePicker() {
  picker.disabled = !picker.disabled
}

Options - Other

id

Now we're getting fancy! If you want to link two instances together to help form a daterange picker, this is your option. Only two picker instances can share an id. The datepicker instance declared first will be considered the "start" picker in the range. There's a fancy getRange method for you to use as well.

const start = datepicker('.start', { id: 1 })
const end = datepicker('.end', { id: 1 })
  • Type - anything but null or undefined

Methods

Each instance of Datepicker has methods to allow you to programmatically manipulate the calendar.

remove

Performs cleanup. This will remove the current instance from the DOM, leaving all others in tact. If this is the only instance left, it will also remove the event listeners that Datepicker previously set up.

const picker = datepicker('.some-input')

/* ...so many things... */

picker.remove() // So fresh & so clean clean.

navigate

Programmatically navigates the calendar to the date you provide. This doesn't select a date, it's literally just for navigation. You can optionally trigger the onMonthChange callback with the 2nd argument.

const picker = datepicker('.some-input')
const date = new Date(2020, 3, 1)

/* ...so many things... */

// Navigate to a new month.
picker.navigate(date)

// Navigate to a new month AND trigger the `onMonthChange` callback.
picker.navigate(date, true)
  • Arguments:
    1. date - JavaScript date object.
    2. trigger onMonthChange - boolean (default is false)

setDate

Allows you to programmatically select or unselect a date on the calendar. To select a date on the calendar, pass in a JS date object for the 1st argument. If you set a date on a month other than what's currently displaying and you want the calendar to automatically change to it, pass in true as the 2nd argument.

Want to unselect a date? Simply run the function with no arguments.

// Select a date on the calendar.
const picker = datepicker('.some-input')

// Selects January 1st 2099 on the calendar
// *and* changes the calendar to that date.
picker.setDate(new Date(2099, 0, 1), true)

// Selects November 1st 2099 but does *not* change the calendar.
picker.setDate(new Date(2099, 10, 1))

// Remove the selection simply by omitting any arguments.
picker.setDate()
  • Arguments:
    1. date - JavaScript date object.
    2. changeCalendar - boolean (default is false)

Note: This will not trigger the onSelect callback.

setMin

Allows you to programmatically set the minimum selectable date or unset it. If this instance is part of a daterange instance (see the id option) then the other instance will be changed as well. To unset a minimum date, simply run the function with no arguments.

// Set a minimum selectable date.
const picker = datepicker('.some-input')
picker.setMin(new Date(2018, 0, 1))

// Remove the minimum selectable date.
picker.setMin()
  • Arguments:
    1. date - JavaScript date object.

setMax

Allows you to programmatically set the maximum selectable date or unset it. If this instance is part of a daterange instance (see the id option) then the other instance will be changed as well. To unset a maximum date, simply run the function with no arguments.

// Set a maximum selectable date.
const picker = datepicker('.some-input')
picker.setMax(new Date(2099, 0, 1))

// Remove the maximum selectable date.
picker.setMax()
  • Arguments:
    1. date - JavaScript date object.

show

Allows you to programmatically show the calendar. Using this method will trigger the onShow callback if your instance has one.

const picker = datepicker('.some-input')
picker.show()

Note: see the "gotcha" below for implementing this method in an event handler.

hide

Allows you to programmatically hide the calendar. If the alwaysShow property was set on the instance then this method will have no effect. Using this method will trigger the onHide callback if your instance has one.

const picker1 = datepicker('.some-input')
const picker2 = datepicker('.some-other-input', { alwaysShow: true })

picker1.hide() // This works.
picker2.hide() // This does not work because of `alwaysShow`.

Note: see the "gotcha" below for implementing this method in an event handler.

Show / Hide "Gotcha"

Want to show / hide the calendar programmatically with a button or by clicking some element? Make sure to use stopPropagation in your event callback! If you don't, any click event in the DOM will bubble up to Datepicker's internal oneHandler event listener, triggering logic to close the calendar since it "sees" the click event outside the calendar. Here's an example on how to use the show and hide methods in a click event handler:

// Attach the picker to an input element.
const picker = datepicker(inputElement, options)

// Toggle the calendar when a button is clicked.
button.addEventListener('click', e => {
  // THIS!!! Prevent Datepicker's event handler from hiding the calendar.
  e.stopPropagation()

  // Toggle the calendar.
  const isHidden = picker.calendarContainer.classList.contains('qs-hidden')
  picker[isHidden ? 'show' : 'hide']()
})

toggleOverlay

Call this method on the picker to programmatically toggle the overlay. This will only work if the calendar is showing!

const picker = datepicker('.some-input')

// Click the input to show the calendar...

picker.toggleOverlay()

getRange

This method is only available on daterange pickers. It will return an object with start and end properties whose values are JavaScript date objects representing what the user selected on both calendars.

const start = datepicker('.start', { id: 1 })
const end = datepicker('.end', { id: 1 })

// ...

start.getRange() // { start: <JS date object>, end: <JS date object> }
end.getRange() // Gives you the same as above!

Properties & Values

If you take a look at the datepicker instance, you'll notice plenty of values that you can grab and use however you'd like. Below details some helpful properties and values that are available on the picker instance.

Property Value
calendar The calendar element.
calendarContainer The container element that houses the calendar. Use it to size the calendar or programmatically check if the calendar is showing.
currentMonth A 0-index number representing the current month. For example, 0 represents January.
currentMonthName Calendar month in plain english. E.x. January
currentYear The current year. E.x. 2099
dateSelected The value of the selected date. This will be undefined if no date has been selected yet.
el The element datepicker is relatively positioned against (unless centered).
minDate The minimum selectable date.
maxDate The maximum selectable date.
sibling If two datepickers have the same id option then this property will be available and refer to the other instance.

Sizing The Calendar

You can control the size of the calendar dynamically with the font-size property!

Every element you see on the calendar is relatively sized in em's. The calendar has a container <div> with a class name of qs-datepicker-container and a font-size: 1rem style on it in the CSS. Simply override that property with inline styles set via JavaScript and watch the calendar resize! For ease, you can access the containing div via the calendarContainer property on each instance. For example:

// Instantiate a datepicker instance.
const picker = datepicker('.some-class')

// Use JavaScript to change the calendar size.
picker.calendarContainer.style.setProperty('font-size', '1.5rem')

Examples

Simplest usage:

const picker = datepicker('#some-id')

Setting up a daterange picker:

const start = datepicker('.start', { id: 1 })
const end = datepicker('.end', { id: 1 })

// NOTE: Any of the other options, as shown below, are valid for range pickers as well.

With all other options declared:

const picker = datepicker('#some-id', {
  // Event callbacks.
  onSelect: instance => {
    // Show which date was selected.
    console.log(instance.dateSelected)
  },
  onShow: instance => {
    console.log('Calendar showing.')
  },
  onHide: instance => {
    console.log('Calendar hidden.')
  },
  onMonthChange: instance => {
    // Show the month of the selected date.
    console.log(instance.currentMonthName)
  },

  // Customizations.
  formatter: (input, date, instance) => {
    // This will display the date as `1/1/2019`.
    input.value = date.toDateString()
  },
  position: 'tr', // Top right.
  startDay: 1, // Calendar week starts on a Monday.
  customDays: ['S', 'M', 'T', 'W', 'Th', 'F', 'S'],
  customMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  customOverlayMonths: ['😀', '😂', '😎', '😍', '🤩', '😜', '😬', '😳', '🤪', '🤓 ', '😝', '😮'],
  overlayButton: 'Go!',
  overlayPlaceholder: 'Enter a 4-digit year',

  // Settings.
  alwaysShow: true, // Never hide the calendar.
  dateSelected: new Date(), // Today is selected.
  maxDate: new Date(2099, 0, 1), // Jan 1st, 2099.
  minDate: new Date(2016, 5, 1), // June 1st, 2016.
  startDate: new Date(), // This month.
  showAllDates: true, // Numbers for leading & trailing days outside the current month will show.

  // Disabling things.
  noWeekends: true, // Saturday's and Sunday's will be unselectable.
  disabler: date => (date.getDay() === 2 && date.getMonth() === 9), // Disabled every Tuesday in October
  disabledDates: [new Date(2050, 0, 1), new Date(2050, 0, 3)], // Specific disabled dates.
  disableMobile: true, // Conditionally disabled on mobile devices.
  disableYearOverlay: true, // Clicking the year or month will *not* bring up the year overlay.

  // ID - be sure to provide a 2nd picker with the same id to create a daterange pair.
  id: 1
})

License

MIT

Copyright 2017 - present, Aaron Cordova

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

datepicker's People

Contributors

fiji404 avatar jdtibbs avatar jvlobo avatar pryley avatar qodesmith avatar steffen8608 avatar sundholmm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

datepicker's Issues

'qs-arrow' selector click function don't call onMonthChange

Hello. Thanks for your package.

But, I click 'qs-arrow' selector and this code don't work

onMonthChange: function(instance) { console.log(instance.currentMonthName); }

Besides, I think you need to create a property 'disableOutMonth'. This property prevents you from changing the date range that is declared 'minDate' and 'maxDate'.

Example:

{ minDate: new Date(2018, 5, 14), maxDate: new Date(2018, 6, 15), disableOutMonth: true }

When user click 'qs-arrow' selector user has access only June and Jule month.

datepicker not working in iOS

The datepicker is working great for me everywhere except on iOS (safari and chrome). Whenever I try to click on a date it does not register and will not dismiss once open on the input.

disabledDates dosent's work

here is my codes

var options = {
minDate: new Date(),
position: 'c',
customMonths: ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
customDays: ['周天','周一','周二','周三','周四','周五','周六'],
disabledDates: [new Date('27/6/2018'), new Date('28/5/2018')],
onSelect: function(instance) {
// Show which date was selected.
console.log(instance.dateSelected.toLocaleString());
}
}
var picker = datepicker('.date',options);

Readonly field trigger click event

We have a following problem: set a input as disabled does accessibility ignores the field. To avoid this, I set input field as readonly, but click event still open datepicker.
That's a way to remove a click listener by demand, without remove datepickers instance?

When entering a year it jumps right through and sends a submit event

Hi,

I really love your datepicker. I tried a lot of them and either they are to bloated or they don't fit in my garbage css styles. This one is great, fits in real nice without hassle.

Though I have an issue, when I enter the year and press return it dismisses the dialog and submits the form. Tried to do a event.preventdefault onHide. But that didn't help.

Regards,
Dion

Feature Request: Option to disable datepicker on touch-enabled devices

This is how I do it, but it would be handy as an option.

var startDate = document.querySelector('#start-date');
var endDate = document.querySelector('#end-date');
var onEv = (type, el, handler) => el.addEventListener(type, handler, false);

if('ontouchstart' in window) {
    // Device is touch-enabled so change the input type to "date" in order to get the date keyboard
    [startDate, endDate].forEach(function(el) {
        onEv('touchstart', el, (ev) => ev.target.type = 'date');
        onEv('focusout', el, (ev) => ev.target.value || (ev.target.type = 'text'));
    });
}
else {
    // Device is not touch-enabled so we load the datepicker
    var dateStart = startDate && datepicker('#start-date');
    var dateEnd = endDate && datepicker('#end-date');
}

Here we are using the native date keyboard instead of the datepicker on a touch-enabled device:

img_5573

IE compatibility?

I have some IE9/10 users and the datepicker doesn't seem to work - works fine on Chrome. Is this a known issue?

Feature: Possibility to disable year overlay

Would be a great feature if you could disable the year overlay using a simple boolean in options.
Great work on the picker btw, its really lightweight and can be used in other frameworks :)

onSelect not being fired

I'm trying to use the date picker with etch and its not firing the onSelect event.

My code looks like this:

    datePicker(this.refs.input, {
      dateSelected: new Date(this.value),
      onSelect: function(){
        console.dir('selected')
      },
      onShow: function(){
        console.log('show')
      },
      onHide: function(){
        console.log('hide')
      }
    })

If I watch the console show and hide get logged but onSelect does not. It also doesn't update the input with new value.

Manual date input

Maybe this is actually a feature and I just don't understand the point of it, but why is manual typing of the date prevented? More specifically, why is the manual input limited to 4 numbers?

I can see this making sense in the custom "Year" input, but why not have the ability to let the user enter a custom date in the field?

First day of the week

Hi! Thanks for the great plugin!

I can't seem to find a way to set Monday as the first day of the week. Is it possible?

Problem using includes with dom elements on some devices

It appears that some devices do not support the use of includes for looking for a dom element.

In the debug version on line 644

const onCal = path.includes(calendar);  

will not work on some devices.

A simple fix is

var onCal = calendar.contains(target);  

which seems to work on all devices I have tested.

Multiple Define error

When using this library with another require style library such as dojo, i know.. forgive me, defining the library after or following the dojo library causes a multiple define error to be thrown.

In your typical index.html file:
src="dojo"
src="js-datepicker"

ERROR

Reversing the order so that the datepicker is first resolves the issues.

Feature Request: disableIfDateIsSupported

This would be similar to the already existing disableMobile, but it would disable the plugin if the browser natively supports the type="date" field of an input.

Basically, the plugin will become just a fallback in case the browser doesn't have a native date picker solution.

Possible code for checking if the browser supports type="date":

var isDateInputSupported = function(){
var elem = document.createElement('input');
elem.setAttribute('type','date');
elem.value = 'foo';
return (elem.type == 'date' && elem.value != 'foo');
}

if (!isDateInputSupported())  // or.. !Modernizr.inputtypes.date
  $('input[type="date"]').datepicker();

Source: https://developers.google.com/web/updates/2012/08/Quick-FAQs-on-input-type-date-in-Google-Chrome

Would you consider a PR for this?

How reset selected date?

I don't understand why don't create reset button date after user selected date? How reset date. If user want delete all dates on calendar?

Add feature "dateDisabled"

Hello. Thanks for your package.

But, I can't send date array, which disable this date. For example I want to exclude 11 April and 13 June. If I will can to use options
dateDisabled: [ new Date(2018, 3, 11), new Date(2018, 5, 13) ] and this date switch to qs-disabled, I will enjoy 👍 )

'Fixed' Positioning option for small devices

This is a great datepicker, ideal for what I needed. However I had a problem positioning the calendar on a small device such as a mobile phone in portrait mode where all of the current options often end up with part of the calendar off screen.

I have modified the code to include a 'fixed' positioning option that positions the calendar in the middle of the view port. I have attached the
datepicker.zip
modified version in case you are interested in including the option in the base (you may be able to improve on my method as well).

Cheers.

noWeekends: true and startDay: 1 causes monday and sunday to be disabled

I'm useing datepicker with the following settings;

datepicker('input#datum', {
	minDate:   new Date(),
	startDate: new Date(),
	startDay: 1,
	noWeekends: true,
	formatter: function (a, b) {
		var day = (b.getDate().toString().length === 1) ? "0" + b.getDate() : b.getDate();
		var month = (b.getMonth().toString().length === 1) ? "0" + b.getMonth() : b.getMonth();

		a.value = day + "-" + month + "-" + b.getFullYear();
	}
});

Because the first day is monday, now the monday and sunday are disabled (https://www.dropbox.com/s/1039sp29xscnddc/Schermafdruk%202018-07-18%2014.15.58.png?dl=0)

WCAG 2.0 Accessibility coverage.

The following issues presented themselves when running this through an accessibility tool:

image

Is it possible to get aria-labels applied to these elements?

Bug / Enhancement: Multiple Datepicker on a page, with one invocation

I'm using the class .fancyDatePicker (as I prefer yours over the one included in Materialize-CSS, and theirs already uses datepicker), and when you make multiple instances on a page only the first one works. The rest perform no action on being clicked. I realise I could make multiple invocation for each instance, but it'd be nice if they'd all work with the single invocation.

Context

I'm making an app with express/node that's largely around CMA's (Comparative Market Analysis), so it's really common to have stuff like Sale Date, Date Listed, etc. Currently looking at a form with 8 instances of .fancyDatePicker.

Your Environment

  • Version used: Most Recent
  • Browser Name and version: Chrome, Most Recent
  • Operating System: Windows 7

Not working on iOS devices.

On Android it works perfectly, but on any ios devices, it doesn't work at all... Was inspecting in browserstuck but there is no error or anything it just not trigger or instanciated datepicker I guess. Any ideas?

Feature Request: Month Selector

Hello again!
Been using your datepicker's in our app for a bit now, and I absolutely love them. The only thing I'm asked consistently is if there is a way to change the overlay behavior so that once you type in a year, you are next shown the months, click your month, now shown the dates for that month. This would solve users that are in December having to click the arrow 12 times to get to December. Is something like that feasible?

Babel preset-env removal breaks compatibility with IE

Hi, in 4.0.10 you have removed babel preset-env from your webpack config claiming that it's no longer used. In fact it was - compare your minified builds from dist between 4.0.9 and 4.0.10. The latter doesn't work on IE because arrow functions appeared in the compiled code (that should be ES5-compatible). I think you should bring it back (and by the way switch to a different building tool such as rollup - webpack seems to be an overkill there).

Display dates of previous and next month within current month

Not an issue, rather a suggestion: by default, when displaying the days within a month, there are empty spaces on top and on bottom on the location where the days of the previous and next month should be. Could there be a way to display those days (in a different markup, like how weekends can be given a different markup) through a setting? Sometimes, design-wise, one could want to enable this.
In that case, an additional suggestion is to also be able to click on a day in a previous/next month and navigate to that previous/next month.

[Question] Programatically show the calendar?

I did look for the doc about this but it does not seem to be possible,
still I'm asking: is it possible to programatically show the calendar?
Something like

let cal = datepicker(".myclass");
cal.show();

The goal is to include the calendar in a more complex user flow than a simple click on an element...
Meanwhile I may just simulate a click to the bound class but it is not optimal.

Thank you for your great job!

Date format?

Am I blind? I dont see where to set the date format.

disabler: mulitple days?

Hello. Thank you for this plugin.

Is it possible to disable multiple days of a week with disabler? For example, a location is only open on Mondays and Thursdays so cannot accept payment on other days, therefore disable (noWeekends:true and disabler: multiple days). I think I must be reading the docs wrong.
Thank you
Edit: Yes I was reading the documents wrong. I should have kept looking. thank you.

Datepicker opens on init ver 5.0.0

After updating to the new 5.0.0, after the datepicker component is created first time on init it opens automatically.

datepicker.hide() is not working for the first time on init, then works normally

Implement daterange capabilities

Let's get datepicker to also be a date range picker!

Currently it's a really hacky process to make two datepicker instances function as a single date range picker. Within the two-calendars branch I'm currently working on adding date range functionality. You'll be able to tie 2 pickers together to form a range picker.

Stay tuned!

Incorrect current date

I've just implemented datepicker on a form, but it appears to be highlighting August 23 as today's date, as opposed to July 23 as it should. An off-by-one error?

Namespace CSS classnames

Nothing broken, but the class names are so common ['controls', 'datepicker'] they really need to be namespaced to fit in universally w/other peoples' work while not breaking visually.

Recommend: 'qds-datepicker', 'qds-controls', etc.

Bug / Enhancement: Multiple Instance with One Invocation

I'm using the class .fancyDatePicker (as I prefer yours over the one included in Materialize-CSS, and theirs already uses datepicker), and when you make multiple instances on a page only the first one works. The rest perform no action on being clicked. I realise I could make multiple invocation for each instance, but it'd be nice if they'd all work with the single invocation.

Context

I'm making an app with express/node that's largely around CMA's (Comparative Market Analysis), so it's really common to have stuff like Sale Date, Date Listed, etc. Currently looking at a form with 8 instances of .fancyDatePicker.

Your Environment

  • Version used: Most Recent
  • Browser Name and version: Chrome, Most Recent
  • Operating System: Windows 7

LICENSE?

I don't see a license listed anywhere, is that on purpose?

Minimal example does not work

The minimal example does not work. It requires a dateSelected.
The minimal example is:
var picker = datepicker('#dp', {dateSelected: new Date()});

datepicker + webpack

I'm trying to use the plugin with webpack. The datepicker is loading in vendors.js and in app.js I call the datepicker but i'm getting this error datepicker is not defined. Any help?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.