Как сделать календарь на js

от admin

How to Use the JavaScript Event Calendar

The JavaScript Event Calendar is designed to permit maximum control over the look and feel of the displayed calendar, while still making it easy to specify events that should be displayed. The look of the calendar is almost entirely controlled by a Cascading Style Sheet (either a linked CSS file, or styles embedded in the page). Basically, you’ll follow these steps:

  1. Download the latest .JS file to your own web site, and reference it on the page where you want to display the calendar.
  2. (optional but recommended) Define CSS settings to customize the look of the calendar.
  3. Put a <div> on your page where you want the calendar to appear, with a unique id.
  4. Create a new JEC object, indicating the id of the div (and any optional settings).
  5. Define one or more events (the .defineEvents() function can be invoked multiple times, and each invocation can define multiple events).
  6. Show the calendar (by calling the .showCalendar() function).

Each of these steps is described in detail below.

The .JS File

The code for the calendar is contained in a single JavaScript file, which you can get on the Downloads page. Please do NOT link directly to the file on this web server; use a copy on your own server. You’ll add a line to the <head> section of your web page, similar to the following:

  • <html>
  • <head>
  • .
  • .
  • <script type=»text/javascript» src=»https://kilsen.github.io/calendar/%3Cpath-to-local-js-files%3E/calendar-2.4.js»></script>
  • .
  • .
  • </head>
  • .
  • .

CSS Styling

The calendar may be styled in a variety of ways; to do this, it is important to understand how the calendar is marked up as an HTML table.

The <table> will have a class of “JEC” (unless this has been overridden prior to showing the calendar). Thus, “table.JEC” can be used as a selector to style individual table elements.

The <table> will have a <thead> that includes one row, with a single <th> spanning 7 columns and containing the month and year. Think of this as the “heading” of the entire calendar. You can style it like this, for example:

  1. table.JEC thead th <
  2. background-color: #696969;
  3. color: white;
  4. font-size: 16px;
  5. font-weight: bold;
  6. margin: 5px;
  7. >

The <table> will have a <tfoot> that includes one row, containing three <th> elements. The first, spanning 2 columns, will contain a link to the previous month. The second, spanning 3 columns, will contain a drop-down select box for jumping directly to any month. The third, spanning 2 columns, will contain a link to the next month.

The <table> will have a <tbody> that includes all of the actual dates. The first row in the <tbody> will contain 7 <th> elements, each containing the (abbreviated) name of a day of the week (Sun — Sat). Subsequent rows will each contain 7 <td> elements. Each <td> in the <tbody> will display a date. Some will be empty because they represent blank squares in the calendar grid; these will be defined as <td >. The others will have a <div > element that contains only the day of the month. If there are events for a day, they will be displayed in a <div > that immediately follows the date. The text of each event description will be enclosed in a <span> element (unless there is a URL associated with the event, in which case the text will be enclosed in an <a> element). When there are multiple events on the same day, a <br/> element will appear BETWEEN the events (but NOT after the last event). If an event has an image, it will precede the event’s <span> or <a> element.

Table cells (<td>’s) may have one or more of the following classes:

dayBlank for a cell that is a blank square in the calendar dayToday for the cell corresponding to the current date daySpecial for special days of the week (Sunday, for example) dayHasEvent if there is at least one event on the day

Using these classes, it is possible to render the date cell(s) differently by adjusting the cell background, the color of the date (by styling div.date), etc. For example:

  1. table.JEC td.dayToday <
  2. background-color: #eee;
  3. border: 3px solid black;
  4. >

At your option, there are two ways you can specify the styling of the elements in the calendar table. Either you can include an embedded style sheet within your HTML page, or you can link to an external style sheet. The Examples page makes use of two different external linked style sheets, as follows:

  • <html>
  • <head>
  • .
  • .
  • <link rel=»stylesheet» href=»css/jec-grey.css» type=»text/css» />
  • <link rel=»stylesheet» href=»css/jec-styled.css» type=»text/css» />
  • .
  • .
  • </head>
  • .
  • .

TWO different style sheets are linked, because the Examples page includes multiple calendars, each styled differently. (Both of these style sheets are available on the Downloads page.)

As previously noted, the calendar’s <table> is created with a by default, but this class can be overridden (as described later). If you are planning to have multiple calendars on the page, styled differently, you will NEED to override the class name.

Place Your Calendar

Decide where, in the overall layout of your page, you’d like your calendar to appear. Create a <div> element with a unique id attribute, and no content. For example:

  • .
  • .
  • <div ></div>
  • .
  • .

Create the JEC Object

For the remaining steps, you’ll need to add a small bit of JavaScript code, where you’ll create the object, set options, define events, and show the calendar. The first step is to create an instance of the JEC «class” as follows:

  1. <script type=»text/javascript»>
  2. var myCalendar = new JEC(‘myCalendarContainer’);
  3. </script>

In the code above, the string that you pass to the JEC( ) constructor must match the id attribute of the <div> where you want the calendar to appear.

The line above will create the JEC object, but nothing will be displayed. To display the calendar, invoke the .showCalendar( ) function on the object that you created:

  1. <script type=»text/javascript»>
  2. var myCalendar = new JEC(‘myCalendarContainer’);
  3. myCalendar.showCalendar();
  4. </script>

Now, the calendar will appear at the desired place on your page. It will display the current month, and the links and drop-down list will permit the user to select any month within the current year. The definition of events (see below) or the explicit inclusion of options will change that default behavior.

The JEC( ) constructor accepts a second parameter (in addition to the id of the <div> that will contain the calendar). The optional second parameter is an object that can contain a set of name/value pairs, specifying options that will alter the generated calendar. The name/value pairs are specified in JavaScript Object Notation (i.e., “JSON” format). The supported options include:

tableClass the name of the class that will be applied to the calendar <table> element (if not specified, the class name will be “JEC”) firstDayOfWeek the day of the week that should be displayed in the left-most column of the calendar; 1=Sunday, 2=Monday, . . . 7=Saturday (default is Sunday) specialDay the day of the week that should receive a special class (“daySpecial”) so that it can be styled differently than the other days; 1=Sunday, 2=Monday, . . . 7=Saturday (if not specified, then no days will receive the special class) specialDays array of special day numbers, if you need multiple days to receive the special class; for example [ 1, 7 ] for Sunday and Saturday (if this option is specified, it will supersede the single specialDay option) linkNewWindow if true, links (when present for events) will open in a new window; if false, links will open in the current browser window (default=true) dateLinkNewWindow if true, date links (when present) will open in a new window; if false, date links will open in the current browser window (default=false) months array of month names for the months January through February weekdays array of weekday names, from Sunday (“Sun”) through Saturday (“Sat”) firstMonth the first month to make available for display, specified in YYYYMM format (the presence of events will take precedence; you cannot make the calendar range “smaller” than the defined events determine) lastMonth the last month to make available for display, specified in YYYYMM format (the presence of events will take precedence; you cannot make the calendar range “smaller” than the defined events determine)

Below is an example of how a calendar can be created with various options:

  1. var myCal = new JEC(‘myCalendarContainer’, <
  2. tableClass: ‘styledCalendar’,
  3. firstMonth: 201003,
  4. lastMonth: 201010,
  5. firstDayOfWeek: 2,
  6. specialDays: [ 1, 7 ],
  7. linkNewWindow: false,
  8. weekdays: [
  9. «Sunday»,
  10. «Monday»,
  11. «Tuesday»,
  12. «Wednesday»,
  13. «Thursday»,
  14. «Friday»,
  15. «Saturday»
  16. ]
  17. >);

Define Events

This is, after all, a JavaScript EVENT Calendar, and so the definition of the events is perhaps the most important aspect of the tool. The JEC object includes a .defineEvents( ) function, which allows you to specify a list of one or more events, each with its own unique properties. As in the case of the optional parameter to the JEC( ) constructor, the events are specified using JSON. The .defineEvents( ) function accepts an array, and each element in the array is an object that can include the following name/value pairs:

eventDate the date of the event, in the format YYYYMMDD (this is a REQUIRED value) eventTime if specified, this optional value is the time of the event (hour and minute), expressed as a number in «military» (24-hour) format; for example, 315 would mean 3:15 AM, 1930 would mean 7:30 PM, 0 would mean midnight (at the very beginning of the day), and 2359 would mean 1 minute before midnight (at the end of the day); when event times are defined, the events will be sorted for display within the date according to the time eventDescription the description of the event, which will appear in the calendar on the indicated date (this is a REQUIRED value) eventLink if specified, this optional value is the URL of a page to which the event will be linked eventLinkTitle if specified, this optional value is text that pops up when the user “hovers” the mouse over the link eventLinkClass if specified, this optional value is the name of the class that will be applied to the link’s <a> element image if specified, this optional value is the path of an image (relative to the current page on the web server) that will be displayed with the event description on the indicated date imageWidth if specified (and if an image is specified), this optional value is the width of the image in pixels (specifying a width is generally not necessary) imageHeight if specified (and if an image is specified), this optional value is the height of the image in lines (specifying a height is generally not necessary)

Below is an example of a call to the .defineEvents( ) function, to define 4 different events:

  1. myCal.defineEvents(
  2. [
  3. <
  4. eventDate: 20100407,
  5. eventDescription: ‘JEC 2.0 Released’,
  6. eventLink: ‘http://calendar.ilsen.net’,
  7. eventLinkTitle: ‘A JavaScript Event Calendar’
  8. >,
  9. <
  10. eventDate: 20090101,
  11. eventDescription: ‘MonkeysTapping Launched!’,
  12. eventLink: ‘http://monkeystapping.com’
  13. >,
  14. < eventDate: 20100705, eventDescription: 'Kevin\'s Birthday' >,
  15. ]
  16. );

To provide some degree of “backward-compatibility” with the original version of the JavaScript Event Calendar, there’s an additional function: .defineEvent( ). This function allows you to define a single event, by specifying the event’s properties as individual parameters. You would invoke this event once for each individual event. It can accept between 2 and 7 parameters (unused parameters at the end can be omitted). The full format is shown below, followed by several examples:

.defineEvent(eventDate, eventDescription, eventLink, image, imageWidth, imageHeight, eventLinkTitle);

  1. myCal.defineEvent(20100407, ‘JEC 2.0 Released’, ‘http://calendar.ilsen.net’, , , , ‘A JavaScript event Calendar’);
  2. myCal.defineEvent(20090101, ‘MonkeysTapping Launched’, ‘http://monkeystapping.com’, ‘img/monkey.gif’);
  3. myCal.defineEvent(20100705, ‘Kevin\’s Birthday’);

Date Links

In addition to the hyperlinks that can be included with defined events, it is also possible to associate hyperlinks with specific dates. The date number will be “clickable” and can be styled in any way that you like. The JEC object includes a .linkDates( ) function, which accepts an array, and each element in the array is an object that includes the following name/value pairs:

linkedDate the date of the event, in the format YYYYMMDD dateLink the URL of a page to which the date will be linked dateLinkTitle the optional text that pops up when the user “hovers” the mouse over the date

Below is an example of a call to the .linkDates( ) function, to define 2 different date links:

  1. myCal.linkDates(
  2. [
  3. <
  4. linkedDate: 20100407,
  5. dateLink: ‘http://calendar.ilsen.net’
  6. >,
  7. <
  8. linkedDate: 20090101,
  9. dateLink: ‘http://monkeystapping.com’
  10. >
  11. ]
  12. );

Date Classes

There is sometimes a need to apply a particular style to a single date or a group of dates. For example, consider the need to highlight a certain holiday weekend with a background color. The JEC object includes a .styleDates( ) function, which accepts an array, and each element in the array is an object that includes the following name/value pairs:

styledDate the date which should be styled with the class, in the format YYYYMMDD dateClass the class to apply to the date

Читать:
Как сделать отправку формы на почту html

Then, you would use your stylesheet to define whatever specific styles should be applied for that class. Below is an example of a call to the .styleDates( ) function:

  1. myCal.styleDates(
  2. [
  3. <
  4. styledDate: 20110528,
  5. dateClass: ‘memorialDayWeekend’
  6. >,
  7. <
  8. styledDate: 20110529,
  9. dateClass: ‘memorialDayWeekend’
  10. >,
  11. <
  12. styledDate: 20110530,
  13. dateClass: ‘memorialDayWeekend’
  14. >
  15. ]
  16. );

Show the Calendar

As previously noted (above), you can display your calendar by invoking the .showCalendar( ) function of your calendar object. This will display the current month and year. You can also specify a particular month and year, in the format YYYYMM, as a parameter. For example, the following series of lines defines a calendar with some options, creates a couple of events, and displays the calendar for July 2010:

Simple Javascript Calendar With Events (Free Code Download)

Welcome to a tutorial on how to create a simple pure Javascript Calendar. Are you looking to develop a calendar web app, without using any server-side scripts? Be it for a commercial project, school project, or just curiosity – You have come to the correct place. This guide will walk you through how to create a pure Javascript calendar, all made possible with local storage. Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

  • If you want to set the calendar to start the week on Monday instead, set cal.sMon = true in calendar.js .

SCREENSHOT

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

HOW THE CALENDAR WORKS

All right, let us now get into a little more detail on how the calendar works. Not going to explain line-by-line, but here’s a quick walk-through.

PART 1) CALENDAR HTML

  1. <div > The month and year selector.
  2. <div > Where we will display the calendar for the selected month and year.
  3. <dialog > A form to add/edit calendar events.

PART 2) CALENDAR INITIALIZE

  • Get all the HTML elements.
  • Set up the month/year selector.
  • Attach the add/edit event form click and submit handlers.

PART 3) PERIOD “SHIFTER”

Next, pshift() is a simple function to shift the current period forward/backward by one month.

PART 4) DRAW THE CALENDAR

  • (D1) A whole bunch of day/month/year calculations.
  • (D2) The events data is kept in localStorage in a monthly manner ( cal-MONTH-YEAR = JSON ENCODED OBJECT ). Retrieve the events data for the selected month/year, and put it into cal.data .
  • (D3) Do all the calculations in squares = [] first.
  • (D4) “Reset” the current HTML calendar.
  • (D5) Redraw the day names.
  • (D6) Loop through squares to draw the HTML calendar.

PART 5) SHOW/EDIT CALENDAR EVENT

When the user clicks on a date cell, cal.show() will be called. Pretty self-explanatory – We fetch the event from cal.data , then show the add/edit event form.

PART 6) SAVE/DELETE EVENTS DATA

Lastly, these are self-explanatory functions again. We simply update the events data in localStorage .

EXTRA BITS & LINKS

Finally, here are a few more extras that may be useful.

MULTIPLE EVENTS PER DAY?

Of course, we can. Let’s take a look at the current save() function:

We are pretty much storing the event data in data[DAY] = EVENT now. So to allow multiple events on the same day, the general idea is to change the current structure into a multi-dimensional array data[DAY] = [EVENT, EVENT, EVENT] .

  • Add more text field(s) in the HTML.
  • save() to include the extra text field(s).
  • list() to draw the extra data.
  • show() to also populate the extra text field(s).

As you can guess, that will increase the complexity exponentially, turning this into a “not simple tutorial”. This is why I don’t answer the “support multiple events” and “span an event across multiple days” questions – Feel free to challenge yourself though, this simple calendar is a good starting point.

LIMITATIONS

  • Only one event is allowed in a day.
  • The events cannot span multiple days.
  • The Javascript calendar requires the use of local storage. If it is disabled on the browser or not supported, then it will not be able to save the events at all.

But of course, I have released this as an open-source. So feel free to tweak it however you see fit or check out the calendar PWA in the links below for a “better calendar”.

LINKS & REFERENCES

    – MDN – MDN – Code Boxx – Code Boxx
  • Example on CodePen – JS Calendar With Event

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Write a Calendar plugin with Javascript

When we hear about Javascript, we often hear about libraries and frameworks. There are about five gazillion choices today on how to use Javascript. Yet, we often forget that we can still use good old classic Javascript, without frameworks or libraries. In this article, we’ll build a plugin using nothing but vanilla Javascript. This plugin, quite simple, will allow us to include a calendar in an HTML page.

Setting up

We need three files, one HTML file, one CSS file and one Javascript file. Let’s start with our Javascript file, because this will be where we have the most work to do.

Plugin Skeleton

The first thing we need to do is to make our plugin available for our environment. We do this by using an IIFE (Immediately Invoked Function Expression). As you can see, we wrap our first function into parentheses, turning it into an expression that we call right away.

IIFE are useful to encapsulate code. My plugin’s code won’t be accessible from outside the plugin. But we’ll see that later.

Let’s break the code above a little bit:

In the main body of our function we do:

What is root? This is the first parameter of our IIFE, this. So, in a browser, this is the window object. We set window.myCalendar to factory(root) . factory, the second parameter of our IIFE, is a function. This is, in fact, our plugin content.

The beauty of this approach is that window.myCalendar will only contain whatever my function returns. So, I’ll be able to call window.myCalendar.init(), but window.myCalendar.privateVar will be undefined, because it’s not returned by our IIFE.

Importing in our index.html

We already have a plugin! It doesn’t do much, but it works. Let’s create a HTML file and test it out.

We load our Javascript file. I called it simple-calendar.js but name it whatever you wish. Then, after the window is done loading, inside the onload event listener, I’m called myCalendar.init() and console.log the myCalendar.privateVar variable.

Note: window.myCalendar and myCalendar is the same here 😉

So, here’s what I see in my console:

Great! The init function prints what we expected and privateVar is indeed undefined because it is not returned from our IIFE, so our plugin doesn’t know what you are talking about!

The CSS

Let’s get that out of the way, because this is not the point of the article. Create a CSS file and put the following styles inside it:

Don’t forget to import it in our HTML file. In the <head> of our page, add the following line:

<link rel=»stylesheet» href=»calendar.css» />

Of course, replace the calendar.css with the name of your file.

Adding functionality

Ok, it’s very cute, but my plugin still doesn’t do anything here. Let’s begin.

Months, Days and Today

I’ll first need to get the months list, days list and today’s date. I want my calendar to focus on today’s date by default. So, in our plugin, above the private variable, let’s add those:

Good, everything is setup. Now, we can start to modify the DOM to implement our calendar. Obviously, this step needs to be done inside the init function. We want the calendar to appear when we initialize our plugin.

There are a few things we need to do:

Create a header with the name of the current month and the current year. This header will also have next and previous buttons to navigate between months.

Below the header, we will have the list of days, from Sunday to Monday.

Finally, we will have the days in the current month.

The header

We have here just a few elements added with Javascript. We don’t use anything fancy, just the classic Javascript API with createElement, appendChild and setAttribute. We created our div element for our header, that will contain the current’s month name. We also created our previous and next buttons.

Notice this line:

let element = document.getElementById(«calendar»);

This element is what will contain our calendar. We put it inside an element with the id calendar. This is a choice I made, but we’ll make it customizable later. But that means we need to add an element with the proper id in our HTML:

That’s it for the HTML. And sure enough, we can see the header in our page.

Header Calendar

Let’s keep going!

Add the list of days and the month’s cells

Now, let’s add the cells that will contain the days of our current month. One thing we’ll need to be careful about: the «empty» days at the beginning of a month. Our week starts on Sunday, but if our month begins on a Wednesday, we’ll need to fill some empty cells.

For clarity, I’ll put this logic inside its own method.

A lot is going on here!

We first call loadMonth. This function is responsible to display the name of the current month and the current year in the header.

We then call createDaysNamesCells, to display our Sunday to Saturday list of days.

We call createEmptyCellsIfNecessary to display the empty cells if necessary. We give that function the date variable, which is the first day of the current month. By calling getDay() on this variable, we get the index of the day. Because it starts on a Sunday, like our week in our calendar, we can do a simple loop to render the number of empty cells we need.

Finally, we get the number of days in that month and render each cell with the correct day displayed. We’ve added a event listener on each cell to print in the console the timestamp and the date of the chosen day. We also added a class for the current day that will styled with CSS.

And this is the result so far!

The calendar is properly rendered, and when we click on a date, we see the timestamp and the date of the cell we clicked in the console.

Adding interactivity

We need to add three things:

  • When I click on a date, it becomes the selected day.
  • When I click on the previous button, we go to the previous month.
  • When I click on the next button, we go to the next month.

For the first item, we need to add the class today to the correct cell. We also need to remove the today class to the previously selected cell. today is the class name I chose, but you can call it whatever you want. You just need to update your code appropriately. Navigate to where we print to the console the timestamp and the date and change the code to this:

This will properly style the cell you selected.

Finally, we’ll add the next/previous month feature:

We add a event listener for each button. We will use the data-action attribute we created to know if we clicked the next or the previous button. data-action is either equal to 1 or -1. We modify the currentMonth variable and call loadMonth again because we need to update the calendar’s content.

Как сделать календарь на js

Напишите функцию createCalendar(elem, year, month) .

Вызов функции должен создать календарь для заданного месяца month в году year и вставить его в elem .

Календарь должен быть таблицей, где неделя – это <tr> , а день – это <td> . У таблицы должен быть заголовок с названиями дней недели, каждый день – <th> , первым днём недели должен быть понедельник.

Например, createCalendar(cal, 2012, 9) сгенерирует в cal следующий календарь:

P.S. В этой задаче достаточно сгенерировать календарь, кликабельным его делать не нужно.

Для решения задачи сгенерируем таблицу в виде строки: "<table>. </table>" , а затем присвоим в innerHTML .

Похожие статьи