Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <!--
  No HTML here,
  it gets attached to the document body by Preact (JavaScript)
-->
              
            
!

CSS

              
                :root {
  --primary-color: #673ab7;
  --primary-color-light: #9a67ea;
  --primary-color-dark: #320b86;
  
  --secondary-color: #ffc400;
  --secondary-color-light: #fff64f;
  --secondary-color-dark: #c79400;
  
  --primary-text-color-dark: rgba(0,0,0,.87);
  --secondary-text-color-dark: rgba(0,0,0,.57);
  --disabled-text-color-dark: rgba(0,0,0,.13);
  
  --primary-text-color-light: rgba(255,255,255,.87);
  --secondary-text-color-light: rgba(255,255,255,.57);
  --disabled-text-color-light: rgba(255,255,255,.13);
  
  --font-stack: 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  
  --primary-card-color: #fff;
  --primary-background-color: #f2f2f2;
  
  --box-shadow-lvl-1: 0 1px 3px rgba(0, 0, 0, 0.12),
                      0 1px 2px rgba(0, 0, 0, 0.24);
  --box-shadow-lvl-2: 0 3px 6px rgba(0, 0, 0, 0.16),
                      0 3px 6px rgba(0, 0, 0, 0.23);
  --box-shadow-lvl-3: 0 10px 20px rgba(0, 0, 0, 0.19),
                      0 6px 6px rgba(0, 0, 0, 0.23);
  --box-shadow-lvl-4: 0 14px 28px rgba(0, 0, 0, 0.25),
                      0 10px 10px rgba(0, 0, 0, 0.22);
}

*, *:before, *:after {
  box-sizing: border-box;
}

body, html {
  overflow-x: hidden;
  font-family: var(--font-stack);
  background-color: var(--primary-background-color);
  color: var(--primary-text-color-dark);
  margin: 0;
  padding: 0;
  position: absolute;
  top: 0;
  left: 0;
  transition: background-color .22s;
  min-width: 100vw;
  min-height: 100vh;
  
  &.darkTheme {
    --primary-text-color-dark: rgba(255,255,255,.87);
    --secondary-text-color-dark: rgba(255,255,255,.57);
    --disabled-text-color-dark: rgba(255,255,255,.13);

    --primary-text-color-light: rgba(0,0,0,.87);
    --secondary-text-color-light: rgba(0,0,0,.57);
    --disabled-text-color-light: rgba(0,0,0,.13);
    
    --primary-card-color: #424242;
    --primary-background-color: #303030;
  }
}

body {
  padding-top: 56px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

a {
  text-decoration: none;
  font-weight: 700;
  color: inherit;
  
  &:hover, &:focus {
    color: var(--secondary-color-dark);
    outline: none;
    text-decoration: underline;
  }
}

main, article {
  transition: background-color .22s;
  background-color: var(--primary-card-color);
  width: calc(100% - 32px);
  height: auto;
  box-shadow: var(--box-shadow-lvl-1);
  margin: 16px auto;
  max-width: 700px;
  padding: 8px 16px;
  border-radius: 3px;
  text-align: center;
  
  h1 {
    line-height: 32px;
    font-size: 28px;
    margin: 0;
    padding: 16px 0;
  }
  
  p {
    text-align: justify;
    line-height: 1.5;
    margin: 0;
    margin-bottom: 16px;
  }
  
  .infoBox {
    background: var(--primary-color);
    color: rgba(255,255,255,.87);
    padding: 8px 16px;
    display: inline-block;
    margin-bottom: 16px;
    border-radius: 3px;
    
    &.red {
      background: #ff8a80;
      color: rgba(0,0,0,.87);
    }
  }
  
  button {
    cursor: pointer;
    appearance: none;
    background: transparent;
    border: none;
    font-size: 16px;
    line-height: 1;
    padding: 8px 16px;
    border-radius: 3px;
    color: var(--primary-text-color);
    transition: background .13s;
    margin-bottom: 16px;
    
    &:hover, &:focus {
      outline: none;
      background: var(--disabled-text-color-dark);
    }
  }
}

article {
  margin-bottom: 56px;
}

footer {
  position: absolute;
  bottom: 16px;
  width: 100%;
  text-align: center;
}

.datePicker {
  text-align: left;
  background: var(--primary-card-color);
  border-radius: 3px;
  z-index: 200;
  position: fixed;
  height: auto;
  max-height: 90vh;
  width: 90vw;
  max-width: 448px;
  transform-origin: top left;
  transition: transform .22s ease-in-out, opacity .22s ease-in-out;
  top: 50%;
  left: 50%;
  opacity: 0;
  transform: scale(0) translate(-50%, -50%);
  user-select: none;

  &.datePicker--opened {
    opacity: 1;
    transform: scale(1) translate(-50%, -50%);
  }
  
  .datePicker--titles {
    border-top-left-radius: 3px;
    border-top-right-radius: 3px;
    padding: 24px;
    height: 100px;
    background: var(--primary-color);

    h2, h3 {
      cursor: pointer;
      color: #fff;
      line-height: 1;
      padding: 0;
      margin: 0;
      font-size: 32px;
    }

    h3 {
      color: rgba(255,255,255,.57);
      font-size: 18px;
      padding-bottom: 2px;
    }
  }

  nav {
    padding: 20px;
    height: 56px;

    h4 {
      width: calc(100% - 60px);
      text-align: center;
      display: inline-block;
      padding: 0;
      font-size: 14px;
      line-height: 24px;
      margin: 0;
      position: relative;
      top: -9px;
      color: var(--primary-text-color);
    }

    i {
      cursor: pointer;
      color: var(--secondary-text-color);
      font-size: 26px;
      user-select: none;
      border-radius: 50%;
      
      &:hover {
        background: var(--disabled-text-color-dark);
      }
    }
  }
  
  .datePicker--scroll {
    overflow-y: auto;
    max-height: calc(90vh - 56px - 100px);
  }

  .datePicker--calendar {
    padding: 0 20px;

    .datePicker--dayNames {
      width: 100%;
      display: grid;
      text-align: center;
      
      // there's probably a better way to do this, but wanted to try out CSS grid
      grid-template-columns: calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7);

      span {
        color: var(--secondary-text-color-dark);
        font-size: 14px;
        line-height: 42px;
        display: inline-grid;
      }
    }

    .datePicker--days {
      width: 100%;
      display: grid;
      text-align: center;
      grid-template-columns: calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7) calc(100% / 7);

      span {
        color: var(--primary-text-color-dark);
        line-height: 42px;
        font-size: 14px;
        display: inline-grid;
        transition: color .22s;
        height: 42px;
        position: relative;
        cursor: pointer;
        user-select: none;
        border-radius: 50%;

        &::before {
          content: '';
          position: absolute;
          z-index: -1;
          height: 42px;
          width: 42px;
          left: calc(50% - 21px);
          background: var(--primary-color);
          border-radius: 50%;
          transition: transform .22s, opacity .22s;
          transform: scale(0);
          opacity: 0;
        }
        
        &[disabled=true] {
          cursor: unset;
        }

        &.datePicker--today {
          font-weight: 700;
        }

        &.datePicker--selected {
          color: rgba(255,255,255,.87);

          &:before {
            transform: scale(1);
            opacity: 1;
          }
        }
      }
    }
  }
  
  .datePicker--selectYear {
    padding: 0 20px;
    display: block;
    width: 100%;
    text-align: center;
    max-height: 362px;
    
    span {
      display: block;
      width: 100%;
      font-size: 24px;
      margin: 20px auto;
      cursor: pointer;
      
      &.selected {
        font-size: 42px;
        color: var(--primary-color);
      }
    }
  }

  div.datePicker--actions {
    width: 100%;
    padding: 8px;
    text-align: right;

    button {
      margin-bottom: 0;
      font-size: 15px;
      cursor: pointer;
      color: var(--primary-text-color);
      border: none;
      margin-left: 8px;
      min-width: 64px;
      line-height: 36px;
      background-color: transparent;
      appearance: none;
      padding: 0 16px;
      border-radius: 3px;
      transition: background-color .13s;

      &:hover, &:focus {
        outline: none;
        background-color: var(--disabled-text-color-dark);
      }
    }
  }
}

.datePicker--background {
  z-index: 199;
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background: rgba(0,0,0,.52);
  animation: fadeIn .22s forwards;
}
              
            
!

JS

              
                let { render, h, Component } = preact;
/**@jsx h*/

class DatePicker extends Component {
  
  closeDatePicker() {
		this.props.closeFunction(); // Function gets passed by parent
	}
  
  /**
  * Gets fired when a day gets clicked.
  * @param {object} e The event thrown by the <span /> element clicked
  */
	dayClicked(e) {
    
    const element = e.target; // the actual element clicked
 
		if (element.innerHTML === '') return false; // don't continue if <span /> empty
    
    // get date from clicked element (gets attached when rendered)
		const date = new Date(element.getAttribute('date'));
    
    // update the state
	  this.setState({ currentDate: date });
	}
  
  /**
  * returns days in month as array
  * @param {number} month the month to display
  * @param {number} year the year to display
  */
  getDaysByMonth(month, year) {
    
    let calendar = [];
    
    const date = new Date(year, month, 1); // month to display
    
    const firstDay = new Date(year, month, 1).getDay(); // first weekday of month
    const lastDate = new Date(year, month + 1, 0).getDate(); // last date of month
    
    let day = 0;
    
    // the calendar is 7*6 fields big, so 42 loops
    for (let i = 0; i < 42; i++) {
      
      if (i >= firstDay && day !== null) day = day + 1;
      if (day > lastDate) day = null;
      
      // append the calendar Array
      calendar.push({
        day: (day === 0 || day === null) ? null : day, // null or number
        date: (day === 0 || day === null) ? null : new Date(year, month, day), // null or Date()
        today: (day === this.now.getDate() && month === this.now.getMonth() && year === this.now.getFullYear()) // boolean
      });
    }
    
    return calendar;
  }
  
  /**
  * Display previous month by updating state
  */
  displayPrevMonth() {
    if (this.state.displayedMonth <= 0) {
      this.setState({
        displayedMonth: 11,
        displayedYear: this.state.displayedYear - 1
      });
    }
    else {
      this.setState({
        displayedMonth: this.state.displayedMonth - 1
      });
    }
  }
  
  /**
  * Display next month by updating state
  */
  displayNextMonth() {
    if (this.state.displayedMonth >= 11) {
      this.setState({
        displayedMonth: 0,
        displayedYear: this.state.displayedYear + 1
      });
    }
    else {
      this.setState({
        displayedMonth: this.state.displayedMonth + 1
      });
    }
  }
  
  /**
  * Display the selected month (gets fired when clicking on the date string)
  */
  displaySelectedMonth() {
    if (this.state.selectYearMode) {
      this.toggleYearSelector();
    }
    else {
      if (!this.state.currentDate) return false;
      this.setState({
        displayedMonth: this.state.currentDate.getMonth(),
        displayedYear: this.state.currentDate.getFullYear()
      });
    }
  }
  
  toggleYearSelector() {
    this.setState({ selectYearMode: !this.state.selectYearMode });
  }
  
  changeDisplayedYear(e) {
    const element = e.target;
    this.toggleYearSelector();
    this.setState({ displayedYear: parseInt(element.innerHTML, 10), displayedMonth: 0 });
  }
  
  /**
  * Pass the selected date to parent when 'OK' is clicked
  */
  passDateToParent() {
    if (typeof this.props.dateReciever === 'function') this.props.dateReciever(this.state.currentDate);
    this.closeDatePicker();
  }
  
  componentDidUpdate() {
    if (this.state.selectYearMode) {
      document.getElementsByClassName('selected')[0].scrollIntoView(); // works in every browser incl. IE, replace with scrollIntoViewIfNeeded when browsers support it
    }
  }
  
  constructor() {
    super();
    
    this.closeDatePicker = this.closeDatePicker.bind(this);
		this.dayClicked = this.dayClicked.bind(this);
    this.displayNextMonth = this.displayNextMonth.bind(this);
    this.displayPrevMonth = this.displayPrevMonth.bind(this);
    this.getDaysByMonth = this.getDaysByMonth.bind(this);
    this.changeDisplayedYear = this.changeDisplayedYear.bind(this);
    this.passDateToParent = this.passDateToParent.bind(this);
    this.toggleYearSelector = this.toggleYearSelector.bind(this);
    this.displaySelectedMonth = this.displaySelectedMonth.bind(this);
    
    this.monthArrShortFull = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ]
    
    this.monthArrShort = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ]
    
    this.dayArr = [
			'Sun',
			'Mon',
			'Tue',
			'Wed',
			'Thu',
			'Fri',
			'Sat'
		]
    
    this.now = new Date()
    
    this.yearArr = []
    
    for (let i = 1970; i <= this.now.getFullYear() + 30; i++) {
      this.yearArr.push(i);
    }
    
    this.state = {
      currentDate: this.now,
      displayedMonth: this.now.getMonth(),
      displayedYear: this.now.getFullYear(),
      selectYearMode: false
    }
  }
  
  render({ opened }) {
    
    const { currentDate, displayedMonth, displayedYear, selectYearMode } = this.state;
    
    return (
      <div>
				<div class={"datePicker " + (opened && "datePicker--opened")} >
          
					<div class="datePicker--titles">
					  <h3 style={{
                color: selectYearMode ? 'rgba(255,255,255,.87)' : 'rgba(255,255,255,.57)'
              }} onClick={this.toggleYearSelector}>{currentDate.getFullYear()}</h3>
						<h2 style={{
                color: !selectYearMode ? 'rgba(255,255,255,.87)' : 'rgba(255,255,255,.57)'
              }} onClick={this.displaySelectedMonth}>
              {this.dayArr[currentDate.getDay()]}, {this.monthArrShort[currentDate.getMonth()]} {currentDate.getDate()}
            </h2>
					</div>

					{!selectYearMode && <nav>
						<i onClick={this.displayPrevMonth} class="material-icons">&#xE314;</i>
						<h4>{this.monthArrShortFull[displayedMonth]} {displayedYear}</h4>
						<i onClick={this.displayNextMonth} class="material-icons">&#xE315;</i>
					</nav>}
          
          <div class="datePicker--scroll">
            
            {!selectYearMode && <div class="datePicker--calendar" >
              
              <div class="datePicker--dayNames">
                {['S','M','T','W','T','F','S'].map(day => <span>{day}</span>)}
              </div>
              
              <div onClick={this.dayClicked} class="datePicker--days">
                
                {/*
                  Loop through the calendar object returned by getDaysByMonth().
                */}
                
                {this.getDaysByMonth(this.state.displayedMonth, this.state.displayedYear)
                  .map(
                    day => {
                      let selected = false;
                      
                      if (currentDate && day.date) selected = (currentDate.toLocaleDateString() === day.date.toLocaleDateString());
                      
                      return (<span
                        class={(day.today ? 'datePicker--today ' : '') + (selected ? 'datePicker--selected' : '')}
                        disabled={!day.date}
                        date={day.date}
                       >
                        {day.day}
                      </span>)
                    }
                  )
                }
                
              </div>
              
            </div>}
            
            {selectYearMode && <div class="datePicker--selectYear">
              
              {this.yearArr.map(year => (
                <span class={(year === displayedYear) ? 'selected' : ''} onClick={this.changeDisplayedYear}>
                  {year}
                </span>
              ))}
              
            </div>}
            
            {!selectYearMode && <div class="datePicker--actions">
              <button onClick={this.closeDatePicker}>CANCEL</button>
              <button onClick={this.passDateToParent}>OK</button>
            </div>}
            
          </div>
				</div>
        
				<div class="datePicker--background" onClick={this.closeDatePicker} style={{
					display: opened ? 'block' : 'none'
				}}
				/>
        
			</div>
    )
  }
}


class App extends Component {
  
  openDatePicker() {
    this.setState({ datePickerOpened: true });
  }
  
  closeDatePicker() {
    this.setState({ datePickerOpened: false });
  }
  
  toggleDarkTheme() {
    document.body.classList.toggle('darkTheme');
  }
  
  /**
  * Gets passed to DatePicker and fired when date is selected and 'OK' is clicked.
  * @param {object} date the date object of the selected date
  */
  dateReciever(date) {
    this.setState({ pickedDate: date });
  } 
  
  constructor() {
    super();
    
    this.state = {
      datePickerOpened: false
    }
    
    this.openDatePicker = this.openDatePicker.bind(this);
    this.closeDatePicker = this.closeDatePicker.bind(this);
    this.dateReciever = this.dateReciever.bind(this);
  }
  
  render() {
    
    const {
      datePickerOpened
    } = this.state;
    
    return (
      <div>
        <main>
          <h1>Material Design Date Picker 📅</h1>
          <div class="infoBox">A reusable date-picker component build only with <a href="https://preactjs.com/">PreactJS</a>, no MomentJS or other library. Build in Chrome, briefly tested on Edge and Firefox (Quantum). Also only in Pacific Time Zone (don't know if this affects anything).</div>
          <button onClick={this.openDatePicker}>{this.state.pickedDate ? this.state.pickedDate.toLocaleDateString() : 'Pick a date'}</button>
          <button onClick={this.toggleDarkTheme}>Toggle Dark Theme</button>
          
          
          {/*   THE DATEPICKER:   */}
          <DatePicker closeFunction={this.closeDatePicker} opened={datePickerOpened} dateReciever={this.dateReciever} />
          
          
          {this.state.pickedDate && <div class="infoBox">You picked {this.state.pickedDate.toLocaleDateString()}</div>}
        </main>
        <article>
          <h1>About</h1>
          <p>
            I build this date picker component because I needed a fast easy-to-use Preact/React solution to pick dates following the material design guidelines.
          </p>
          <p>
            But I wasn't satisfied by anything I found so I took some time and made this one. If you want to use it for your own projects feel free to copy-paste the DatePicker class!
          </p>
          <p>
            I tried to comment any code that may be unclear, but if you still have any questions, you can ask me via <a href="https://twitter.com/MariusNiver" >Twitter</a> :)
          </p>
        </article>
        <footer>&lt;coded /&gt; with ❤️ and ☕ by <a href="https://niveri.me">Marius Niveri</a></footer>
      </div>
    )
  }
}

// Finally attach app to document body
render(<App />, document.body);
              
            
!
999px

Console