Introduction
This is an example of how to use CustomElements
to create useful tags.
The example creates a <k-date>
tag that can be used to display dates in both absolute and relative mode (i.e., like 5 Jun 2018, 10 days ago, 20 days hence, yesterday, etc.).
Background
WebComponents like CustomElement
and ShadowDOM
are going to be the most important and productive web technology in the coming days. You can easily find many tutorials for understanding the topic online. Here is one from Mozilla (check it out for an introduction to WebComponents).
Since only Google Chrome supports WebComponents out of the box at this time (23-Jun-2018), we need to use polyfills. You can get polyfills from here. For the sake of convenience, I have included it in the downloadable code zip file.
Using the Code
Here, I will only describe how to use the code, as this is only a "Tip" (and hence is expected to short). Please go to the above mentioned Mozilla article for understanding the basic concepts. If you have any questions regarding this code, you can ask me in the comments or via email.
First and foremost, you need to include the JS file that defines the new tag.
<head>
<!--
<!--
<script src="k-date.js"></script>
</head>
Now you can use the new date tag (k-date)
as any regular HTML tags. To illustrate the features of the new <k-date>
tag, here are some examples and their expected results.
<k-date></k-date>
<!--
<br />
A date value can be assigned as an attribute:
<k-date value="2018-06-05"></k-date>
<!--
<k-date value="1 jan 2015"></k-date>
<!--
<br />
JavaScript stores dates as number of milliseconds since January 01,
1970, 00:00:00 UTC (Universal Time Coordinated).
<br />
You can also provide date value as number of milliseconds since January 01, 1970, 00:00:00 UTC
<k-date value="1528137000000"></k-date>
<!--
<br />
Date value can also be relative to current date as number of days
<k-date value="+1"></k-date>
<!--
<k-date value="-5"></k-date>
<!--
<br />
If the date value is invalid then
<k-date value="abc"></k-date>
<!--
<br />
The default invalid date string can be overridden as
<k-date value="abc" default="Unknown"></k-date>
<!--
<br />
The date can also be to be relative to current date by adding and 'relative' attribute
<k-date value="2018-06-24" relative></k-date>
<!--
<k-date value="2018-06-20" relative></k-date>
<!--
<k-date value="-1" relative></k-date>
<!--
<k-date value="2018-05-01" relative></k-date>
<!--
<k-date value="2018-01-01" relative></k-date>
<!--
<br />
If the date is in relative mode then hovering over the tag will show the actual date value as a tooltip.
Try it out to discover all the nuances of <k-date>
tag.
As an example, I think that the most relevant use of this tag can be in comments/blog/forum posts to display the date of posting in relative mode. The following image shows all the ways that this tag can be used.
So in conclusion, experiment and enjoy with the code.
Thank you for reading this tip.