gengns ES

An entry from the gengns log, written by Génesis García Morilla · · CSS3, HTML5, JavaScript

HTML input time

Firefox Nightly version (at least) is going to support (but poorly) HTML input date and HTML input time. You will be able to use natively widgets in updated browsers without depending on third party libraries. However, there are some limitations, if you have ever dealt with an HTML input time you know what it is about, try to set up maximum or minimum hours/minutes and/or change from 12 hours format to 24 hours and viceversa. By now, the best solution to avoid headaches or wastes of time is to use 2 inputs of the type number and a pinch of JS.

HTML

<div>
  <input type="number" min="0" max="23" placeholder="23">:
  <input type="number" min="0" max="59" placeholder="00">
</div>

CSS

  div {
    background-color: white;
    display: inline-flex;
    border: 1px solid #ccc;
    color: #555;
  }
  
  input {
    border: none;
    color: #555;
    text-align: center;
    width: 60px;
  }

JavaScript

document.querySelectorAll('input[type=number]')
  .forEach(e => e.oninput = () => {
    // Always 2 digits
    if (e.value.length >= 2) e.value = e.value.slice(0, 2);
    // 0 on the left (doesn't work on FF)
    if (e.value.length === 1) e.value = '0' + e.value;
    // Avoiding letters on FF
    if (!e.value) e.value = '00';
  });
Open in JSFiddle

Tags: input, time