Giter Site home page Giter Site logo

hotel-datepicker's Introduction

Hotel Datepicker

A pure Javascript date range picker for hotels. Requires Fecha 4.0.0 or above and supports all modern browsers. Check the demo here.

Hotel Datepicker Thumbnail

Installation

As a module:

Install with:

npm i hotel-datepicker

Then import the modules with:

import * as fecha from "fecha";
import HotelDatepicker from "hotel-datepicker";
import "hotel-datepicker/dist/css/hotel-datepicker.css";

As a script:

Download Fecha.

[BREAK CHANGE] Use Fecha 4.0.0 or above.

Include files:

<link href="/path/to/hotel-datepicker.css" rel="stylesheet" /><!-- Optional -->
<script src="/path/to/fecha.js"></script>
<script src="/path/to/hotel-datepicker.min.js"></script>

Usage

Initialize with vanilla JS.

<input id="input-id" type="text" />
var hdpkr = new HotelDatepicker(document.getElementById("input-id"), options);

Options

format

  • Type: String
  • Default: YYYY-MM-DD

The date format string.

infoFormat

  • Type: String
  • Default: YYYY-MM-DD

The date format string in the info box. If not set, it uses the format option.

ariaDayFormat

  • Type: String
  • Default: dddd, MMMM DD, YYYY

The date format string in the aria label strings.

separator

  • Type: String
  • Default: -

The separator string used between date strings.

startOfWeek

  • Type: String
  • Default: sunday

Default start week: sunday or monday.

startDate

  • Type: Date or String
  • Default: new Date()

The start view date. All the dates before this date will be disabled.

endDate

  • Type: Date or String or Boolean
  • Default: false

The end view date. All the dates after this date will be disabled.

minNights

  • Type: Number
  • Default: 1

Minimum nights required to select a range of dates.

maxNights

  • Type: Number
  • Default: 0

Maximum nights required to select a range of dates.

minNightsMultiple

  • Type: Boolean
  • Default: false

If true, only ranges that are multiples of minNights are allowed.

selectForward

  • Type: Boolean
  • Default: false

If true, the selection of the second date must be after the first date. If false, you can select a range of dates in both directions.

disabledDates

  • Type: Array
  • Default: []

An array of strings in this format: 'YYYY-MM-DD' (note the ''). All the dates passed to the list will be disabled.

enableCheckout

  • Type: Boolean
  • Default: false

If true, allows the checkout on a disabled date. But with a criteria. Let's say we have these disabled dates: 03 April 2020 and 04 April 2020. With this option enabled, an user can still select the first date (03 April 2020) for the checkout. But not 04 April 2020.

noCheckInDates

  • Type: Array
  • Default: []

An array of strings in this format: 'YYYY-MM-DD' (note the ''). All the dates passed to the list will not allow a check-in on that day.

noCheckOutDates

  • Type: Array
  • Default: []

An array of strings in this format: 'YYYY-MM-DD' (note the ''). All the dates passed to the list will not allow a check-out on that day.

disabledDaysOfWeek

  • Type: Array
  • Default: []

An array of strings of day names in your language (same names used in i18n['day-names']): 'Monday' (note the '' and the uppercase).

noCheckInDaysOfWeek

  • Type: Array
  • Default: []

An array of strings of day names in your language (same names used in i18n['day-names']): 'Monday' (note the '' and the uppercase).

noCheckOutDaysOfWeek

  • Type: Array
  • Default: []

An array of strings of day names in your language (same names used in i18n['day-names']): 'Monday' (note the '' and the uppercase).

["Monday", "Tuesday", "Wednesday"];

container

  • Type: Element
  • Default: ''

An element for putting the datepicker. If not set, the datepicker will be appended to the parent of the input.

inline

  • Type: Boolean
  • Default: false

Render the datepicker inline.

clearButton

  • Type: Boolean
  • Default: false

If true, a button to clear the selected dates is shown. Works only when showTopbar is true.

submitButton

  • Type: Boolean
  • Default: false

If true, a submit button is shown. Works only when inline and showTopbar are true.

submitButtonName

  • Type: String
  • Default: ``

The name of the button to reference the form-data. Works only when submitButton is true.

animationSpeed

  • Type: String
  • Default: .5s

The duration (in seconds) of the animation (open/close datepicker).

hoveringTooltip

  • Type: Boolean or Function
  • Default: true

Shows a tooltip when hovering a date. It can be a custom function:

hoveringTooltip: function(nights, startTime, hoverTime) {
    return nights;
}

showTopbar

  • Type: Boolean
  • Default: true

Show/hide the toolbar.

topbarPosition

  • Type: String
  • Default: top

Set the position of the toolbar.

autoClose

  • Type: Boolean
  • Default: true

Close the datepicker after the selection of the second date.

preventContainerClose

  • Type: Boolean
  • Default: false

When a click is done outside the datepicker container, the datepicker closes. Use this option to disable this behavior.

moveBothMonths

  • Type: Boolean
  • Default: false

Move both months when clicking on the next/prev month button.

onDayClick

  • Type: Function
  • Default: false

Run a custom function every time a day is clicked:

onDayClick: function() {
    console.log('Day clicked!');
}

onOpenDatepicker

  • Type: Function
  • Default: false

Run a custom function when the datepicker is opened:

onOpenDatepicker: function() {
    console.log('Datepicker opened!');
}

onSelectRange

  • Type: Function
  • Default: false

Run a custom function when a range is selected:

onSelectRange: function() {
    console.log('Date range selected!');
}

extraDayText

  • Type: Function
  • Default: false

Run a custom function to show extra text in day cells:

extraDayText: function(date, attributes) {
    if (attributes.class.includes("datepicker__month-day--visibleMonth")) {
        console.log(date);
        console.log(attributes);
        return "<span>$150</span>";
    }
}

i18n

[BREAK CHANGE] Two new options has been introduced in the v.3: month-names-short and day-names-short. Previously, the short day name version ('Sun', 'Mon', 'Tue', etc) was used in the day-names option. Now, the day-names option uses the long version.

  • Type: Object

Default:

i18n: {
    selected: 'Your stay:',
    night: 'Night',
    nights: 'Nights',
    button: 'Close',
    clearButton: 'Clear',
    submitButton: 'Submit',
    'checkin-disabled': 'Check-in disabled',
    'checkout-disabled': 'Check-out disabled',
    'day-names-short': ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    'day-names': ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    'month-names-short': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    'month-names': ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    'error-more': 'Date range should not be more than 1 night',
    'error-more-plural': 'Date range should not be more than %d nights',
    'error-less': 'Date range should not be less than 1 night',
    'error-less-plural': 'Date range should not be less than %d nights',
    'info-more': 'Please select a date range of at least 1 night',
    'info-more-plural': 'Please select a date range of at least %d nights',
    'info-range': 'Please select a date range between %d and %d nights',
    'info-range-equal': 'Please select a date range of %d nights',
    'info-default': 'Please select a date range',
    'aria-application': 'Calendar',
    'aria-selected-checkin': 'Selected as check-in date, %s',
    'aria-selected-checkout': 'Selected as check-out date, %s',
    'aria-selected': 'Selected, %s',
    'aria-disabled': 'Not available, %s',
    'aria-choose-checkin': 'Choose %s as your check-in date',
    'aria-choose-checkout': 'Choose %s as your check-out date',
    'aria-prev-month': 'Move backward to switch to the previous month',
    'aria-next-month': 'Move forward to switch to the next month',
    'aria-close-button': 'Close the datepicker',
    'aria-clear-button': 'Clear the selected dates',
    'aria-submit-button': 'Submit the form'
}

Methods

getValue()

This function is called when the picker gets the date range string from the input.

setValue()

This function is called when the picker sets the input value.

API

open()

Opens the datepicker.

close()

Closes the datepicker.

getDatePicker()

Gets the datepicker DOM element.

setRange(d1, d2)

Sets the date range value.

clear()

Clears the datepicker value.

getNights()

Gets the number of nights selected. Returns 0 otherwise.

destroy()

Destroys the datepicker.

Events

afterClose

You can listen for this event when the datepicker closes.

var input = document.getElementById("input-id");

input.addEventListener(
    "afterClose",
    function () {
        console.log("Closed!");
    },
    false
);

Keyboard Shortcuts

  • ←/→: Move backward (left) and forward (right) by one day.
  • ↑/↓: Move backward (up) and forward (down) by one week.
  • PGUP/PGDN: Switch months.
  • HOME/END: Go to the first or last day of a week.
  • : Select the date in focus or trigger click on button in focus.
  • ESC: Return to the date input field.

Versioning

Maintained under the Semantic Versioning guidelines.

Credits

Hotel Datepicker was initially developed as a fork of jQuery Date Range Picker Plugin by Chunlong. But it was entirely rewritten in the version 2. It is now an independent project.

License

MIT Copyright (c) 2024 Benito Lopez

hotel-datepicker's People

Contributors

benitolopez avatar enjoy2000 avatar gummibeer avatar jordygit avatar samwx avatar squallcs12 avatar thomasleveil avatar wql7013 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hotel-datepicker's Issues

Demo

Hi Benito, there seems to be an issue with demo. Input fields won't init date-picker's. Is there something missing in installation instruction?

Conditional required nights (opposite of #52)

Hi,

The solution as offered in #52 is a good one, but I'm looking for another option. Would it be possible to have the end date clickable even it is lower than the required number of nights?

So if there is an availability of 3 nights, but required nights is 5, I'd like to lower the required nights to 3 for that period- and make it possible to select an end date.

That would help to get a better fill rate.

Pre-Determined date range

Hi,

This looks awesome and I'm really hoping I can use it on a project I'm working on however it has slightly different requirements.

Essentially, instead of hotel booking, it's for trip booking. The requirements are almost identical except instead of allowing the user to choose the date range, it's already pre-determined to 'x days'.

Is there a workaround (or supported functionality) to change the behaviour so that when a user clicks on the first date, the second date is automatically selected (highlighting the days inbetween)?

Destroy calendar, or refresh

Hello, I want to update the calendar's disabledDates after it was #initalised, I am thinking that the most easy way would be to destroy the calendar and initiate it again, how can I do that?

If I do this it's good?

$('#datepicker-clientCalendar').remove();

And then reinitialise it with the new options.

"getValue()" Sample usage

Hello,

How do I get these dates if the user has determined the dates?
How to use this method , can you give me an example?

Thank you!

getValue()

This function is called when the picker gets the date range string from the input.

Enabled dates

Is it / would it be possible to provide a whitelist of dates rather than the blacklist of dates for the disabled dates.

Ideally the availability would be in the reverse to what's currently formatted, by inputting the available dates

like it, some way to allow empty end date range

hi, i like your pure js "no jquery" implementation of date range picker

there's some way to allow user choose starter date and let empty the end of the range optionally?

if i must change the code there's no problem, i try but please i need it.

How to change color of input:active?

I want to change the color of the class .datepicker__dummy-input--is-active but i can't.

My vue component:

<template>
  <no-ssr>
    <HotelDatePicker class="color-active" :i18n="dateoptions.i18n" :format="dateoptions.format" DatePickerID="travel" @checkOutChanged="updateDateTo($event)" @checkInChanged="updateDateFrom($event)"/>
  </no-ssr>
</template>

My style:

.datepicker-label{
  font-weight: normal;
  color: #4182e0;
  display: inline-block;
  max-width: 100%;
  margin-bottom: 5px;
}
.color-active .datepicker__dummy-input--is-active{
  color: #4182e0;
}

The class datepicker-label is working perfectly, but when is active not working. The strange is when I inspect the elements the modification appears, but the screen continues the default color(#00ca9d).
foto 1

Left or Right

Hello,

Thank you for this, it's great really!

I have a question, can it be based on the right or left side according to the shape of the page?

Have a nice day.

Logo Proposal

Good day @benitolopez I am a graphic designer and an open-source enthusiast and i would like to propose a logo design for your nice project as a gift for free. I just need you permission first before I begin my design. Thanks and best regards! - Tobaloidee

Impossible dates are clickable

I require at least 5 nights and have a time frame of 3 days between two disabled dates - it's possible to click them for start but not to end the selection.
In my opinion the selection should stop on every click - independent of valid or not. And a nice to have would be to mark the dates that are impossible to book, because of minNights and available nights, as such with a new CSS class.

Doesn't work with keyboard navigation [accessibility,a11y]

Part of the problem is that a lot of the event triggers are things other than buttons.

Expected:

  • Should be able to open the datepicker using only the keyboard (maybe when the text input is focused?)
  • Should be able to change the date using only the keyboard. This can maybe be fixed by adding buttons in each date cell and replacing the month arrow spans with buttons, and moving the event handlers to those button elements.

minNights not consistent with calendar title/message

Very nice datepicker! However, I found a bug that would be great to have fixed: When having set minNights: N as an option where N is an integer, the calendar title/message shows "Please select a date range longer than N night", but it only needs to be longer than N-1 night(s), i.e. minimum N, not minimum N+1, nights. So when setting minNights: 1, it only needs to be longer than 0 night, not longer than 1 night.

image

How can we disable typing?

Hi, this is really a good one for booking system. How can we disable typing. Is there any built in function?

issue with Disable some dates not working.

Hi sir,
I try to make disable dates like thats,
1). one ways

var hdpkr;
       $(document).ready(function () {
           var input = document.getElementById('ppzdate');
           hdpkr = new HotelDatepicker(input, {
             format: 'DD-MM-YYYY',
             autoClose: false,
             disabledDates:  [
               2017-09-27,
               2017-09-23,
               2017-09-26,
               2017-09-28,
               2017-10-01,
               2017-10-11
           ]
           });
           hdpkr.open();
       });

--------------error -------------
image

2). 2nd ways
because getting disabled dates json

var  disabledDates1= ["2017-09-27","2017-09-23","2017-09-26" ...............................]
 var hdpkr;
        $(document).ready(function () {
             var  disabledDates1= [
                2017-09-27,
                2017-09-23,
                2017-09-26,
                2017-09-28,
                2017-10-01,
                2017-10-11
            ]
            var input = document.getElementById('ppzdate');
            hdpkr = new HotelDatepicker(input, {
              format: 'DD-MM-YYYY',
              autoClose: false,
              disabledDates: disabledDates1,
            });
            hdpkr.open();
        });

-----------error-------------------
getting same error..

Notes: otherwise how to i make some dates is disable.

Is inline / open by default calendar possible

Hello,

I was wondering is there a quite simple way to have the calendar inline / already open in it's place when page loads? It would save some clicks for the user and show disabled dates at glance.

Can't insert to container div

I've trying to add calendar to div#calendar-container without luck.

As option:

var datepicker = new HotelDatepicker(document.getElementById('calendar-input'), {
		format: 'DD-MM-YYYY',
		separator: '|',
		startOfWeek: 'monday',
		showTopbar: false,
		autoClose: false,
		container: '#calendar-container'
});

Without container works on input fine.
JS Console give me an error:

TypeError: this.parent.insertAdjacentHTML is not a function. (In 'this.parent.insertAdjacentHTML("beforeend",t)', 'this.parent.insertAdjacentHTML' is undefined)

<div id="calendar-container"></div>
is present in html

Any idea ?

EDIT: I found solution. There must be an object instead of id name:

...
container: document.getElementById('#calendar-container')
...

Set Range not working for specific dates.

Hi, pretty great plugin! I'm unfortunately having some issues with it right now!

If I call something like .setRange( '2018-10-27', '2018-11-01' ); then the whole calendar resets and the range doesn't get applied. This seems to happen to some date ranges but not others. I'm not able to select anything up to 11-04 but .setRange( '2018-10-27', '2018-11-05' ); works.

Do you have any idea why this is happening?

From what I can tell valid does not get set to false in your setRange function

Mininum number of nights in a range of date

I have a very specific problem. In my case, I can have a minimum of night for an selected range of date.

Example, between 2018-10-01 and 2018-10-15, user MUST select a minimum of 3 nights, otherwise, they have no minimum of nights. Can I do something to do this with your plugin?

Select only one date

Congratulations on the fantastic work.
Is it possible to select only one date?

Day in month is disabled without a reason

I found one strange bug, that some day in month is disabled without a reason
calendar-1
.

Steps to reproduce:

  • Go to http://lopezb.com/hoteldatepicker/
  • Go to "Don't close the datepicker after selection" and click in textbox to open calendar
  • Click 30.4.2018. in right calendar
  • Click Right Arrow in April to go to Mai
  • Click Right Arrow in left calendar, to go to April
  • Click 01.05.2018. in right calendar
  • Click 29.04.2018. in left calendar

Now is 30.04.2018. in left calendar disabled, and can't no more be selected.

Buttons don't disable on mobile

On mobile (just one calendar visible) the buttons keep visible all the time. Even if in first/last month.
It should be like on desktop and disable the previous/next button if in first/last month.

One month displayed

Hello.
Is it possible somehow to display only only month without "next"?
The example is in attachment.
Thank you!
screenshot at oct 04 00-57-52

Disabled dates demos

On your demo page, on the "Disable some dates" demo you have six(6) initial dates that are disabled on the calendar. There are two minor issues.

  1. Issue Type: BUG
    When you click/select any first date, the closest disabled date BEFORE the date you clicked/selected is no longer disabled and can now be selected. This can lead to a user choosing an unavailable date.

For example: If Aug 7th, 8th, and 9th are disabled, clicking on any date greater than Aug 9th will make Aug 9th available.

  1. Issue Type: UI/UX
    When you click/select your first date you are stuck with that date. It would be more user friendly if clicking again on that date clears the date if no other date is selected.

These two issues are present with or without "enableCheckout: true"

Other than that, fantastic work!

Add prices in calendar

I have added prices to calendar, but now I must adjust css to style calendar properly, because date cell is now bigger:
calendar-4
Can you point me in right direction, what should I change in sass (_base.scss?), to adjust cell width?
Maybe is there also a better way to add price, instead with <br> tag?

I am not so experienced in css...

I added in constructor of HotelDatepicker two additional parameters, priceDates and priceCurrency:

		this.priceDates = opts.priceDates || [];
		this.priceDatesUsed = this.priceDates.length > 0;
		this.priceCurrency = opts.priceCurrency || '€';

Highlight specific date

Hi.
Is it possible to highlight the specific date / range of dates if, for example, there is a discount on staying and I'l like a customer to notice that?
Thank you.

Can't Show the datepicker on .open() function

The datepicker work perfectly, but doesn't appear if I apply the function .open() to the HotelDatepicker object, by clicking on the element I want. The click event is recorded in the console, so the problem is the hotel-datepicker object. No JS error in the console

picker_options = {
    autoClose: true,
    startDate: today,
    format: 'DD-MM-YYYY',
    startOfWeek: 'monday',
    moveBothMonths: true,
    separator: ' / '
}
var Hotel_Datepicker = new HotelDatepicker(datepicker_input_DOM, picker_options);

$(dom_selected_element).on('click',function(){
     console.log("CLICKED");
     Hotel_Datepicker.open();
});

Month change event like jquery ui datepicker

I am developing a hotel room booking system. For that I am planning to use your wonderful plugin. I have to show in seasons and holidays in calendar. That means, winter starts from Nov 15 to April 25 & Summer starts from May 15 & Oct 10. In between these seasons some days are holidays. In calendar, I need to show holidays and not season days as disabled in calendar. Is it possible with this plugin? Do this plugin support next month change event like jquery ui datepicker.

Inline calendar (for mobile)

First of all, great job on this datepicker :)!

Have you considered an optimization for mobile where the date picker would be inline instead of you having to tap to open it? Perhaps even stack the calendar months on top of each other so the user has to tap less. What do you think?

MinNights of 0 is not working

A global minimum number of nights is forced to be one, ie. you cannot select the same start and end date.

Preconditions:

Version 3.0.1 of hotel-datepicker
Version 2.3.1 od fecha
Browser chrome onmacOS

Changing the demo1 code to:

var demo1 = new HotelDatepicker(input1, 
	{
		minNights: 0
	}
);

does not allow the selection of a single date for start and end date

Disabled Dates Styling

I am using your datepicker with disabledDates: [] AND enableCheckout: true.

Do you have a suggestion how to have different styling on the "enableCheckout" date and the day after the last disabled date in a block of disabled dates?

Best look at the example attached.
checkout_dates

showTopBar option is not working

Preconditions:

Version 3.0.1 of hotel-datepicker
Version 2.3.1 od fecha
Browser chrome onmacOS

Changing the demo1 code to:

var demo1 = new HotelDatepicker(input1, 
				{
					autoClose: true,
					showTopbar: false
				}
			);

does not remove the top bar on the datepicker

image

Fecha variable problem

[Error] ReferenceError: Can't find variable: fecha
setFechaI18n (hotel-datepicker.js:106)
getDateString (hotel-datepicker.js:182)
compareMonth (hotel-datepicker.js:1045)
init (hotel-datepicker.js:237)
HotelDatepicker (hotel-datepicker.js:70)
Kod globalny (script.js:1)

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.