Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

3 Steps Simple Pure Javascript Calendar (With Events)

INTRODUCTION
JAVASCRIPT ONLY ORGANIZATION

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 curiousity – 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 to find out how!

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

 

CONFESSION
AN HONEST DISCLOSURE

Quick, hide your wallets! I am an affiliate partner of Google, eBay, Adobe, Bluehost, Clickbank, and more. There are affiliate links and advertisements throughout this website. Whenever you buy things from the evil links that I recommend, I will make a commission. Nah. These are just things to keep the blog going, and allows me to give more good stuff to you guys - for free. So thank you if you decide to pick up my recommendations!


 

NAVIGATION
TABLE OF CONTENTS

Step 1
The HTML

Step 2
The CSS

Step 3
The Javascript

Extra
Download & More

Closing
What’s Next?

 

 

STEP 1
THE HTML

Let us start with the foundation of this project, the HTML landing page that will display the calendar.

THE SCRIPT

index.html


  
    Simple Javascript Calendar

THE EXPLANATION

This simple HTML should be straightforward enough, there are only 3 sections here:

  • Right at the top is the date/period selector.
  • In the middle is a
     container where we will display the calendar.
  • At the bottom is another 
     container to show the add/edit event docket.

    STEP 2
    THE CSS

    Next, we move on with the CSS, which are just some cosmetics. Feel free to change it to fit the theme of your own project.

    calendar.css
    /* [SITE] */
    html, body, textarea, input{
      font-family: arial;
    }
    
    /* [PERIOD SELECTOR] */
    #selector{
      padding: 10px;
    }
    #selector select, #selector input[type=button]{
      padding: 10px;
      font-size: 1.2em;
    }
    
    /* [CALENDAR] */
    #calendar{
      width: 100%;
      border-collapse: collapse;
    }
    #calendar tr td{
      border: 1px solid #ccc;
      padding: 20px 5px;
      width: 14.28%;
      vertical-align: top;
    }
    td.blank{
      background: #eee;
    }
    tr.day td{
      background: #ba3423;
      color: #fff;
      font-weight: bold;
    }
    .evt{
      margin-top: 5px;
      padding: 5px;
      background: #fff2dd;
      color: #555;
      font-size: 0.75em;
      max-height: 5em;
      overflow: hidden;
    }
    
    /* [ADD/EDIT EVENT] */
    #event form{
      margin-top: 10px;
      padding: 10px;
      background: #f2f2f2;
    }
    #event h1{
      padding: 0;
      margin: 0;
    }
    #evt-date{
      margin: 10px 0;
      font-weight: bold;
    }
    #event textarea{
      display: block;
      padding: 10px;
      margin: 10px 0;
      min-width: 320px;
      resize: none;
    }
    #event input[type=button], #event input[type=submit]{
      padding: 10px;
      font-size: 1.05em;
    }

    STEP 3
    THE JAVASCRIPT

    Finally, we deal with the Javascript, the part that will do almost all of the heavy lifting work.

    THE SCRIPT

    calendar.js
    var cal = {
      mName : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], // Month Names
      data : null, // Events for the selected period
      sDay : 0, // Current selected day
      sMth : 0, // Current selected month
      sYear : 0, // Current selected year
      list : function () {
      // cal.list() : draw the calendar for the given month
    
        // BASIC CALCULATIONS
        // Note - Jan is 0 & Dec is 11 in JS.
        // Note - Sun is 0 & Sat is 6
        cal.sMth = parseInt(document.getElementById("month").value);
        cal.sYear = parseInt(document.getElementById("year").value);
        var daysInMth = new Date(cal.sYear, cal.sMth+1, 0).getDate(),
            startDay = new Date(cal.sYear, cal.sMth, 1).getDay(),
            endDay = new Date(cal.sYear, cal.sMth, daysInMth).getDay();
    
        // INIT & LOAD DATA FROM LOCALSTORAGE
        cal.data = localStorage.getItem("cal-" + cal.sMth + "-" + cal.sYear);
        if (cal.data==null) {
          localStorage.setItem("cal-" + cal.sMth + "-" + cal.sYear, "{}");
          cal.data = {};
        } else {
          cal.data = JSON.parse(cal.data);
        }
    
        // DRAWING CALCULATION
        // Determine the number of blank squares before start of month
        var squares = [];
        if (startDay != 0) {
          for (var i=0; i";
            if (cal.data[squares[i]]) {
              cCell.innerHTML += "
    " + cal.data[squares[i]] + "
    "; } cCell.addEventListener("click", function(){ cal.show(this); }); } cRow.appendChild(cCell); if (i!=0 && (i+1)%7==0) { cTable.appendChild(cRow); cRow = document.createElement("tr"); } } // REMOVE ANY ADD/EDIT EVENT DOCKET document.getElementById("event").innerHTML = ""; }, show : function (el) { // cal.show() : show edit event docket for selected day // PARAM el : Reference back to cell clicked // FETCH EXISTING DATA cal.sDay = el.getElementsByClassName("dd")[0].innerHTML; // DRAW FORM var tForm = "

    " + (cal.data[cal.sDay] ? "EDIT" : "ADD") + " EVENT

    "; tForm += "
    " + cal.sDay + " " + cal.mName[cal.sMth] + " " + cal.sYear + "
    "; tForm += ""; tForm += ""; tForm += ""; // ATTACH var eForm = document.createElement("form"); eForm.addEventListener("submit", cal.save); eForm.innerHTML = tForm; var container = document.getElementById("event"); container.innerHTML = ""; container.appendChild(eForm); }, save : function (evt) { // cal.save() : save event evt.stopPropagation(); evt.preventDefault(); cal.data[cal.sDay] = document.getElementById("evt-details").value; localStorage.setItem("cal-" + cal.sMth + "-" + cal.sYear, JSON.stringify(cal.data)); cal.list(); }, del : function () { // cal.del() : Delete event for selected date if (confirm("Remove event?")) { delete cal.data[cal.sDay]; localStorage.setItem("cal-" + cal.sMth + "-" + cal.sYear, JSON.stringify(cal.data)); cal.list(); } } }; // INIT - DRAW MONTH & YEAR SELECTOR window.addEventListener("load", function () { // DATE NOW var now = new Date(), nowMth = now.getMonth(), nowYear = parseInt(now.getFullYear()); // APPEND MONTHS var mth = document.getElementById("month"); for (var i = 0; i

    THE EXPLANATION

    Holy cow! This looks like a whole bunch of confusing code, but there are actually only 4 functions, plus a small init fragment at the bottom:

    • When the window is fully loaded, the script will populate the  of both the month and year selectors.
    • Next, it proceeds to draw the calendar with cal.list(). In a nutshell, it extracts any previous events data from the localStorage, and does some super ninja calculations to draw the calendar table.
    • The rest pretty much deals with the user actions. cal.show() will fire up when the user clicks on a specific date. Draws the add/edit event form.
    • cal.save() will adapt the event details, and update the localStorage data as the user hits “save”.
    • Similarly, cal.del() will remove an event and update the localStorage data as the user hits “delete”.

    THE SUMMARY

    FunctionDescription
    cal.list()Draws the calendar for the selected period.
    cal.show()Show the add/edit event docket (when the user clicks on a date).
    cal.save()Save the event.
    cal.del()Delete the event.
    PropertyDescription
    cal.mNameAn array with the names of the months.
    cal.dataTemporary storage for the events of the current month.
    cal.sDayTemporary storage for the currently selected day.
    cal.sMthTemporary storage for the currently selected month.
    cal.sYearTemporary storage for the currently selected year.

    EXTRA
    DOWNLOAD & MORE

    That’s all for the code, and here is the download link as promised – Plus a small extra that may be useful to you.

    PHP MYSQL CALENDAR

    Want a “serious” PHP calendar with a database instead? Check out my other guide:

    3 Steps to Build a Simple PHP Calendar (With Events)

    LIMITATIONS

    • Only one event allowed in a day.
    • The events cannot span across 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.

    SOURCE 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.

    CLOSING
    WHAT’S NEXT?

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

    The post 3 Steps Simple Pure Javascript Calendar (With Events) appeared first on Code Boxx.



This post first appeared on Xxxxxxxxx, please read the originial post: here

Share the post

3 Steps Simple Pure Javascript Calendar (With Events)

Email
Facebook
Pinterest
Twitter
×

Subscribe to Xxxxxxxxx

Get updates delivered right to your inbox!

Thank you for your subscription

×