DS Log
In my blog, I delve into the world of programming web technologies, Linux, Unix-like, and graphic design using free tools on Linux.
KINGCODE
KingCode Editor (ex Texty Editor) is my project developed using Java Swing. Project is still in development and in beta version. I plan to add additional features focused for PYTHON, PHP, JAVA, C, JS and BASH.
Read more ↗
VUE on Linux
In this guide, I'll walk you through the step-by-step process of setting up Vue.js on your Linux system, empowering you to create dynamic and interactive web applications. Let's harness the power of Vue.js together on the Linux platform!
Read more ↗
Symfony PHP
Dive into the world of Symfony PHP with this comprehensive introduction. In this guide, you'll learn the essential steps to create and manage posts and users, empowering you to build dynamic web applications with ease.
Read more ↗
Trying Linux from Windows
How to set up a PHP development server on Ubuntu 22.04
Text editors
List of text editors for developers.
Read more ↗
Fonts
Important fonts everyone needs to know.
Read more ↗
Try Linux from Windows
Here are some quick videos I made showing how to try out Linux Mint on Windows.
Read more ↗
Sunday, July 28, 2024
Building a Customizable Calendar with JavaScript
In this blog post, we will explore a simple yet powerful JavaScript function to create a customizable responsive mobile-friendly calendar. This function, DSCalendar, allows you to define calendar configurations, add markers for specific dates, and handle user interactions via callbacks. Whether you need a calendar for a scheduling application or just to display dates, this function provides a solid foundation.
For example, I'm using this for my Wordpress plugin and this works well with Bootstrap.
Function Overview
The DSCalendar function is designed to generate a calendar with the following customizable configurations:
Type: The calendar type, with 'eu' being the default.
Callback: A function to handle click events on calendar days.
Year: The year for which the calendar is generated.
Markers: Special markers for specific dates.
Target: The HTML element where the calendar will be rendered.
Code Breakdown
Initial Configuration
First, we define the initial configuration object:
function DSCalendar(conf = null) {
let returnObject = {
conf: {
type: null,
callback: null,
year: null,
markers: null,
target: null,
}
};
If a configuration is provided, it merges with the default configuration:
if (conf !== null) {
returnObject.conf = {
...returnObject.conf,
...conf,
type: conf.type || 'eu',
callback: conf.callback || 'ds_myAction',
year: conf.year || new Date().getFullYear(),
markers: conf.markers || null,
target: conf.target || null,
};
}
Setting the Target Element
The target element is determined next. If the target is not provided, a new div is created and appended to the body:
if (returnObject.conf.target !== null) {
let tempElement = document.getElementById(returnObject.conf.target);
if (tempElement === null) throw new Error("DSCalendar: target element with id: " + returnObject.conf.target + " is not found!");
returnObject.conf.target = tempElement;
} else {
returnObject.conf.target = document.createElement('div');
returnObject.conf.target.id = "ds-calendar-generated";
document.body.appendChild(returnObject.conf.target);
}
Helper Functions
The following helper functions are defined to assist with calendar generation:
Name |
Decription |
validateMonthYear |
Validates the month and year values. |
getMonthDays |
Returns the days of the month along with their corresponding weekdays. |
getMonthName |
Returns the name of the month. |
getDaysFromMonday |
Calculates the days from Monday for the first day of the month. |
getDaysUntilSundayFromLast |
Calculates the days until Sunday from the last day of the month. |
Drawing the Calendar
The drawEuMonth function generates the HTML for a given month:
let drawEuMonth = function(year, month) {
if (!validateMonthYear(year, month)) {
throw new Error("DSCalendar: invalid year or month integer!");
}
const monthData = getMonthDays(year, month);
const daysFromMonday = getDaysFromMonday(year, month);
const daysUntilSunday = getDaysUntilSundayFromLast(year, month);
let drawDays = function(monthNumbers) {
let htmlBlock = '<tr>';
for (let i = 1; i < monthNumbers.length + 1; i++) {
let day = monthNumbers[i - 1];
if (day === '') {
htmlBlock += `<td data-id="-1" class="empty"></td>`;
} else {
let classList = "day";
let title = "";
if (returnObject.conf.markers !== null) {
let targetDate = day + '.' + month;
let markers = returnObject.conf.markers;
for (let i = 0; i < markers.length; i++) {
if (targetDate === markers[i][0]) {
classList = "day selected";
title = markers[i][1];
}
}
}
if (returnObject.conf.callback !== null) {
let callback = returnObject.conf.callback;
htmlBlock += `<td data-id="${day}.${month}" title="${title}" class="${classList}" onclick="${callback}(this)">${day}</td>`;
} else {
htmlBlock += `<td data-id="${day}.${month}" title="${title}" class="${classList}">${day}</td>`;
}
}
if (i % 7 === 0) {
if (i < monthNumbers.length) {
htmlBlock += '<tr>';
htmlBlock += `\n\n`;
}
}
}
return htmlBlock;
};
let monthNumbers = [];
for (const day in monthData) {
monthNumbers.push(day);
}
monthNumbers = Array(daysFromMonday).fill('').concat(monthNumbers);
monthNumbers = monthNumbers.concat(Array(daysUntilSunday).fill(''));
const htmlDayDataBlock = drawDays(monthNumbers);
let monthString = getMonthName(month);
let html = `
<table class="ds-calendar-table table table-bordered">
<thead>
<tr>
<th colspan="7">${monthString}</th>
</tr>
<tr>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
<th>S</th>
</tr>
</thead>
<tbody>
${htmlDayDataBlock}
</tbody>
</table>
`;
return html;
};
Rendering the Calendar
The drawCalendar method assembles the HTML for the entire year and injects it into the target element:
returnObject.drawCalendar = function() {
let fullHtml = "";
if (returnObject.conf.type === 'eu') {
for (let i = 1; i < 13; i++) {
fullHtml += drawEuMonth(returnObject.conf.year, i);
}
}
returnObject.conf.target.innerHTML = fullHtml;
};
return returnObject;
};
Example Usage
To use the DSCalendar function, simply initialize it with your desired configuration and call drawCalendar:
function ds_myAction(that) {
console.log(that);
}
let markerData = [
["22.3", "Hello 1"],
["12.4", "Hello 2"],
["2.2", "Hello 3"]
];
let dsCalendar = DSCalendar({
target: 'ds-calendar',
callback: 'ds_myAction',
markers: markerData
});
dsCalendar.drawCalendar();
Conclusion
The DSCalendar function is a versatile tool for creating dynamic and interactive calendars. By allowing customization of the calendar type, year, markers, and callback functions, it can be tailored to meet various needs. Integrate it into your projects to provide users with an intuitive and interactive calendar experience.
In future I plan to add US version and drawing of specific months and update
of calendar notes!
Codepen ↗