HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
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.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
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.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
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.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div ng-app="myApp" class="container">
<h1>AngularJS (v1.4) Timepicker</h1>
<p><em><strong>PRE-RELEASE VERSION:</strong>
This is a prototype.
I am working on an npm release for this component. For
now—should you flatter me by wanting to use this—you will
have to integrate the code into your project yourself.
I have tried to make your life easier by keeping the
code well-organized. Please reach out to me with any
questions (whusterj@gmail.com).</em></p>
<h3>The Timepicker</h3>
<p>This is a timepicker component partly inspired by the Google
Calendar timepicker. It allows for flexible time entry by
typing or by selecting a time from a dropdown menu. It also works
with the AngularJS ng-model and form validation.</p>
<h3>Example</h3>
<form action="#" id="theForm" name="theForm" novalidate ng-cloak>
<p><em>Try entering various time formats,
ex: '1pm', '1 pm', '1', '13', etc.</em></p>
<timepicker id="id_time" name="time" default-time="7pm"
class="form-field" label="Enter time:"
ng-model="theTime" required
></timepicker>
<ng-messages for="theForm.time.$error"
class="error-list">
<ng-message when="required" class="error-text">
<em>Please enter a time.</em>
</ng-message>
</ng-messages>
</form>
<div class="hero-box" tabindex="0" ng-cloak>
<h4>SELECTED TIME</h4>
<h2 ng-bind="theTime | date:'h:mm a'" ng-if="theTime"></h2>
<h2 ng-if="!theTime">Invalid Time</h2>
</div>
<h3>Why?</h3>
<p>There are a few decent timepicker implementations out there,
but none of them had all the features I needed:</p>
<ul>
<li>Support for en-US locale in either 12-hour or 24-hour format.</li>
<li>Flexible, fool-proof time entry by keyboard that makes it hard to type an invalid time.</li>
<li>Time entry from a dropdown list of reasonable times.</li>
<li>WAI-ARIA hooks to help with accessibility, whether using touch, mouse, or keyboard.</li>
<li>Support for AngularJS form validation.</li>
</ul>
<h3>Browser Support</h3>
<p>This component should support all major modern browsers,
including IE 9+. Please contact me if you notice any bugs.</p>
<h3>Time Format Support</h3>
<p>The following JavaScript array demonstrates the various time
formats supported by the component. <a href="http://stackoverflow.com/questions/141348/what-is-the-best-way-to-parse-a-time-into-a-date-object-from-user-input-in-javas" target="_blank">Shout-out to this
Stack Overflow discussion.</a></p>
<pre><code class="javascript">
var acceptedTimes = [
'1:00 pm','1:00 p.m.','1:00 p','1:00pm',
'1:00p.m.','1:00p','1 pm','1 p.m.','1 p',
'1pm','1p.m.', '1p','13:00','13'
];
</code></pre>
<!--
Timepicker Directive Template
Add the directive template to the template cache. In a proper
build system, this would of course be in its own html file.
-->
<script type="text/ng-template" id="timepicker.tpl.html">
<div class="timepicker">
<label>{{ labelText }}</label><br>
<input type="text" ng-model="theTime"
time-input render-on-blur render-on-enter>
<div ng-show="showingChoiceList" class="timepicker-dropdown" ng-cloak>
<div ng-repeat="time in choiceTimes" class="item" id="d{{ time | dateToTimestamp }}"
ng-click="setTime(time)" ng-class="{ selected: isSelectedTime(time) }">
{{ time | date:"shortTime" }}
</div>
</div>
</div>
</script>
<!-- End timepicker directive template -->
</div>
<!-- End ng-app & container -->
@import url(https://fonts.googleapis.com/css?family=Abril+Fatface);
@import url(https://fonts.googleapis.com/css?family=Signika);
/// Variables
@grayLight: rgb(200,200,200);
@grayLighter: rgb(240,240,240);
@grayLightest: rgb(250,250,250);
@redLight: rgb(255,200,200);
/**
* Demo page styles
**/
* {
box-sizing: border-box;
}
body {
font-family: Signika, Arial, Helvetica, sans-serif;
font-weight: 400;
font-size: 18px;
line-height: 1.40;
background: @grayLighter;
}
h1, h2 {
font-family: Abril Fatface, Georgia, serif;
font-weight: 400;
}
h1 {
font-size: 50px;
text-align: center;
}
h2 {
font-size: 37px;
}
code {
font-size: 16px;
}
.container {
max-width: 600px;
margin: 0 auto;
}
.hero-box {
background: white;
border-radius: 12px;
text-align: center;
padding: 24px;
box-shadow: 0 0 3px rgba(0,0,0,0.35);
}
input[type="text"] {
font-size: 14px;
padding: 0.75em;
border-radius: 3px;
border: 2px solid @grayLight;
}
/**
* Timepicker Styles
**/
.timepicker {
margin-bottom: 25px;
&.ng-invalid {
margin-bottom: 0;
& > input {
background: @redLight;
border-color: red;
}
}
&.ng-invalid + .error-list {
display: inline-block;
position: relative;
padding: 0 4px;
top: -5px;
font-size: 14px;
line-height: 1.40;
color: white;
background: red;
}
}
.timepicker-dropdown {
position: absolute;
background: white;
box-shadow: 0 0 6px rgba(0,0,0,0.35);
min-width: 140px;
max-height: 150px;
overflow: auto;
z-index: 1000;
-webkit-user-select: none;
user-select: none;
& > .item {
text-align: right;
line-height: 1.35;
cursor: pointer;
-webkit-user-select: none;
user-select: none;
&.selected {
background: @grayLighter;
}
/* &:hover {
background: @grayLighter;
}*/
}
}
/////// App Initialization
(function () {
'use strict';
angular
.module('myApp', [
'ngMessages',
'myApp.timepicker'
]);
})();
/////// Timepicker Directives
/**
* AngularJS Timepicker Directive for more flexible and
* user-friendly time input.
*
* @author William Huster <whusterj@gmail.com>
* @version 0.0.1
**/
(function () {
'use strict';
angular
.module('myApp.timepicker', [
'myApp.utils'
])
.directive('timepicker', [
'$window', '$document', 'utils',
'elemUtils', 'dateUtils', timepicker
])
.directive('timeInput', ['$filter', 'dateUtils', timeInput])
.directive('renderOnBlur', renderOnBlur)
.directive('renderOnEnter', renderOnEnter);
function timepicker ($window, $document, utils, elemUtils, dateUtils) {
return {
restrict: 'EA',
scope: {
'theTime': '=ngModel',
},
controller: ['$scope', 'utils', 'dateUtils', TimepickerController],
replace: true,
// Template at the bottom of the HTML section
templateUrl: 'timepicker.tpl.html',
link: linker,
};
function TimepickerController ($scope, utils, dateUtils) {
var self = this;
$scope.choiceTimes = [];
$scope.generateChoiceTimes = _generateChoiceTimes;
$scope.selectPrevTime = _selectPrevTime;
$scope.selectNextTime = _selectNextTime;
$scope.isSelectedTime = _isSelectedTime;
$scope.showingChoiceList = false;
$scope.showChoiceList = _showChoiceList;
$scope.hideChoiceList = _hideChoiceList;
$scope.toggleChoiceList = _toggleChoiceList;
$scope.setTime = _setTime;
/// Event listeners
$scope.$watch('theTime', function (newVal, oldVal) {
if (newVal) { $scope.selectedTime = newVal; }
});
// Allow the linker to pass a reference to the
// directive element.
this.init = function (element, inputField, dropdown) {
this.element = element;
this.inputField = inputField;
this.dropdown = dropdown;
};
/// Functions
function _generateChoiceTimes (startingTime) {
for(var i=0; i<48; i++) {
// Create new time and normalize to Jan 1, 1970
var newTime = dateUtils.dateAdd(
startingTime, 'minute', 30*i
);
newTime.setYear(70);
newTime.setMonth(1);
newTime.setDate(1);
// Add to list of choices
$scope.choiceTimes.push(newTime);
}
}
function _selectPrevTime () {
// TODO: choiceTimes could be managed better with
// something like a circular linked list
// with next and prev methods on each node.
// Don't change the selection if dropdown is not showing
if (!$scope.showingChoiceList) { return; }
// Get the next index value, based on the current selection.
// If this is the first item, wrap around to the last item
var selectedIndex = _getSelectedTimeIndex();
var nextIndex = selectedIndex === 0 ? $scope.choiceTimes.length - 1
: selectedIndex - 1;
// Update the selected time
$scope.selectedTime = $scope.choiceTimes[nextIndex];
$scope.$apply();
}
function _selectNextTime () {
// TODO: choiceTimes could be managed better with
// something like a circular linked list
// with next and prev methods on each node.
// Don't change the selection if dropdown is not showing
if (!$scope.showingChoiceList) { return; }
// Get the next index value, based on the current selection.
// If this is the first item, wrap around to the last item
var selectedIndex = _getSelectedTimeIndex();
var nextIndex = selectedIndex === $scope.choiceTimes.length - 1
? 0 : selectedIndex + 1;
// Update the selected time
$scope.selectedTime = $scope.choiceTimes[nextIndex];
$scope.$apply();
}
/**
* Date objects cannot be directly compared. Instead,
* coerce to a `Number` before making the comparison.
**/
function _isSelectedTime (time) {
return Number(time) === Number($scope.selectedTime);
}
/**
* Like the Array.indexOf() method: find the index of
* the current time selection in the array or return `-1`.
**/
function _getSelectedTimeIndex () {
for (var i = 0; i < $scope.choiceTimes.length; i++) {
if (_isSelectedTime($scope.choiceTimes[i])) {
return i;
}
}
return -1;
}
function _showChoiceList (event) {
if ($scope.showingChoiceList === true) { return; }
$scope.showingChoiceList = true;
$scope.$apply();
$document.on('click', _hideChoiceList);
}
function _hideChoiceList (event) {
if ($scope.showingChoiceList === false) { return; }
if (event && (self.inputField[0].contains(event.target)
|| self.dropdown[0].contains(event.target))) {
return;
}
$scope.showingChoiceList = false;
$scope.$apply();
$document.off('click', _hideChoiceList);
}
function _toggleChoiceList (event) {
if ($scope.showingChoiceList) { _hideChoiceList(event); }
else { _showChoiceList(event); }
$scope.$apply();
}
function _setTime(time) {
$scope.theTime = time;
}
}
function linker (scope, element, attrs, tpCtrl) {
// initialize field value
var inputField = element.find('input'),
dropdown = angular.element(
element[0].querySelector('.timepicker-dropdown')
);
// Pass element references to controller
tpCtrl.init(element, inputField, dropdown);
// Initialize scope variables
scope.labelText = attrs.label || '';
scope.theTime = attrs.defaultTime
? dateUtils.parseTimeStringToDate(attrs.defaultTime)
: new Date(1970, 1, 1, 0, 0, 0, 0);
scope.selectedTime = scope.theTime;
scope.generateChoiceTimes(scope.selectedTime);
/// Event Listeners
inputField.on('focus + click', function (event) {
inputField[0].select();
scope.showChoiceList();
_updateDropdownPosition();
scope.$apply();
_updateDropdownScroll();
});
inputField.on('keydown', function (event) {
switch(event.keyCode) {
case 38: // Up arrow
scope.selectPrevTime();
_updateDropdownScroll();
break;
case 40: // Down arrow
scope.selectNextTime();
_updateDropdownScroll();
break;
case 13: // Enter key
scope.setTime(scope.selectedTime);
scope.hideChoiceList();
break;
default: // Any other key
// Any other should close the dropdown
scope.hideChoiceList();
_updateDropdownScroll();
break;
}
});
//
dropdown.on('click', function (event) {
inputField[0].focus();
scope.$apply();
scope.hideChoiceList();
})
// Hide the dropdown menu while resizing. Debounce for performance.
$window.addEventListener('resize', utils.debounce(function () {
dropdown.css({visibility: 'hidden'});
}, 50, true));
$window.addEventListener('resize', utils.debounce(function () {
_updateDropdownPosition();
dropdown.css({visibility: 'visible'});
}, 50));
/// Functions
function _updateDropdownScroll () {
var selectedTimeDiv = _getSelectedTimeDiv();
if (selectedTimeDiv) {
dropdown[0].scrollTop = selectedTimeDiv.offsetTop;
}
}
/**
* Get div corresponding to selected time.
* ids are in the format of 'd' + timestamp
*/
function _getSelectedTimeDiv () {
return dropdown[0].querySelector(
'#d' + String(Number(scope.selectedTime))
);
}
function _updateDropdownPosition () {
// Reposition the dropdown.
// This needs to be called after the dropdown has been revealed, in
// order for the width of the dropdown to be read properly.
var dropdownPosition = elemUtils.below(
inputField[0], dropdown[0]
);
dropdown.css('top', dropdownPosition.top + 'px');
dropdown.css('left', dropdownPosition.left + 'px');
}
}
}
function timeInput ($filter, dateUtils) {
return {
restrict: 'A',
require: 'ngModel',
link: linker,
};
function linker (scope, element, attrs, ngModelCtrl) {
var dateFormat = 'h:mm a';
ngModelCtrl.$formatters = [function (modelValue) {
return $filter('date')(modelValue, dateFormat);
}];
ngModelCtrl.$parsers.unshift(function (viewValue) {
return dateUtils.parseTimeStringToDate(viewValue);
});
}
}
/**
* Re-renders the ng-model attached to an input when the input
* loses focus.
**/
function renderOnBlur () {
return {
restrict: 'A',
require: 'ngModel',
link: linker,
};
function linker (scope, element, attrs, ngModelCtrl) {
element.on('blur', function () {
if (!ngModelCtrl.$modelValue) { return; }
var viewValue = ngModelCtrl.$modelValue;
for (var i = 0; i < ngModelCtrl.$formatters.length; i++) {
viewValue = ngModelCtrl.$formatters[i](viewValue);
}
ngModelCtrl.$viewValue = viewValue;
ngModelCtrl.$render();
});
}
}
/**
* Re-renders the ng-model attached to an input when the
* user presses the `Enter` key while inside the input.
**/
function renderOnEnter () {
return {
restrict: 'A',
require: 'ngModel',
link: linker,
};
function linker (scope, element, attrs, ngModelCtrl) {
element.on('keydown', function (event) {
if(event.keyCode === 13) {
event.preventDefault();
event.stopPropagation();
if (!ngModelCtrl.$modelValue) { return; }
var viewValue = ngModelCtrl.$modelValue;
for (var i = 0; i < ngModelCtrl.$formatters.length; i++) {
viewValue = ngModelCtrl.$formatters[i](viewValue);
}
ngModelCtrl.$viewValue = viewValue;
ngModelCtrl.$render();
}
});
}
}
})();
/////// Utility Services
(function () {
angular
.module('myApp.utils', [])
.factory('utils', utils)
.factory('elemUtils', elemUtils)
.factory('dateUtils', dateUtils)
.filter('dateToTimestamp', dateToTimestamp);
function dateToTimestamp () {
return function (date) {
return date.valueOf();
};
}
function utils () {
var exports = {
debounce: _debounce,
objIndexFromId: _objIndexFromId,
};
return exports;
function _objIndexFromId (source, idVal, idKey) {
/* Retrieve index of object with key and value that match those provided */
idKey = typeof idKey !== 'undefined' ? idKey : 'id';
return source.map(function(x) {return x[idKey]; }).indexOf(idVal);
}
// Debounce function from David Walsh's blog
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function _debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
}
/**
* Library of useful DOM Element operations
**/
function elemUtils () {
var exports = {
// dimensions
outerWidth: _outerWidth,
outerHeight: _outerHeight,
animationDuration: _animationDuration,
// positioning
above: _above,
below: _below,
centerOffset: _centerOffset,
};
return exports;
/// Element dimension functions
function _outerWidth (element) {
/** Get the width of an element including margins */
var elemCSS = window.getComputedStyle(element);
return element.offsetWidth
+ (parseFloat(elemCSS.marginLeft, 10) || 0)
+ (parseFloat(elemCSS.marginRight, 10) || 0);
}
function _outerHeight (element) {
/** Get the height of an element including margins */
var elemCSS = window.getComputedStyle(element);
return element.offsetHeight
+ (parseFloat(elemCSS.marginTop, 10) || 0)
+ (parseFloat(elemCSS.marginBottom, 10) || 0);
}
function _animationDuration (element) {
/* Get the computed animation duration on the element */
var elementCSS = window.getComputedStyle(element);
return parseFloat(elementCSS['animation-duration'], 10);
}
/// Element positioning functions
function _above (parent, child) {
/* Get child position that centers it above parent */
throw new Error('The `Position.above()` method is not yet implemented.');
}
function _below (parent, child) {
/* Get child position that centers it below parent */
var childLeft = _centerOffset(parent).left - (_outerWidth(child) / 2);
var childTop = parent.offsetTop + parent.offsetHeight;
// Align the child element to the left side of the screen
// in edge cases where it would overflow the left side
// or where the screen is skinnier than the child element.
if (childLeft < 0 || window.innerWidth <= _outerWidth(child)) {
childLeft = 0;
} else if (childLeft + _outerWidth(child) > window.innerWidth) {
// Ensure the popover doesn't overflow the right side of the screen.
childLeft = window.innerWidth - _outerWidth(child);
}
return {
top: childTop,
left: childLeft,
};
}
function _centerOffset (element) {
/* Get the left offset (in pixels) of the center of an element */
return {
left: element.offsetLeft + element.offsetWidth / 2,
top: element.offsetTop + element.offsetHeight / 2,
};
}
}
/**
* This service provides some shortcut functions for
* working with dates, especially dates in ISO format,
* which is the date format Angular prefers when working
* with date inputs.
*/
function dateUtils () {
return {
dateAdd: _dateAdd,
parseTimeStringToDate: _parseTimeStringToDate,
};
function _dateAdd(date, interval, units) {
var ret = new Date(date); // don't change original date
switch(interval.toLowerCase()) {
case 'year' : ret.setFullYear(ret.getFullYear() + units); break;
case 'quarter': ret.setMonth(ret.getMonth() + 3*units); break;
case 'month' : ret.setMonth(ret.getMonth() + units); break;
case 'week' : ret.setDate(ret.getDate() + 7*units); break;
case 'day' : ret.setDate(ret.getDate() + units); break;
case 'hour' : ret.setTime(ret.getTime() + units*3600000); break;
case 'minute' : ret.setTime(ret.getTime() + units*60000); break;
case 'second' : ret.setTime(ret.getTime() + units*1000); break;
default : ret = undefined; break;
}
return ret;
}
/**
* Parses partial and complete time strings to a date object.
* Makes time input a lot more user-friendly.
*
* For example, all of the following string inputs should be
* parsed to a date object of today's date and time of 1pm.
*
* var times = ['1:00 pm','1:00 p.m.','1:00 p','1:00pm',
* '1:00p.m.','1:00p','1 pm','1 p.m.','1 p',
* '1pm','1p.m.', '1p','13:00','13'];
*
* NOTE: This version is optimized for the en-US locale in
* either 12-hour or 24-hour format. It may not be
* suitable for all locales. Instaed of re-writing this
* function, it would make more sense to extend our
* capabilities with locale-specific functions.
**/
function _parseTimeStringToDate (timeString) {
if (timeString == '') return null;
var time = timeString.match(/(\d+)(:(\d\d))?\s*(p?)/i);
if (time == null) return null;
var hours = parseInt(time[1],10);
if (hours == 12 && !time[4]) { hours = 0; }
else { hours += (hours < 12 && time[4])? 12 : 0; }
var d = new Date(1970, 1, 1, 0, 0, 0);
d.setHours(hours);
d.setMinutes(parseInt(time[3],10) || 0);
d.setSeconds(0, 0);
return d;
}
}
})();
// Kick off HighlightJS for demo
hljs.initHighlightingOnLoad();
Also see: Tab Triggers