Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 29, 2021 03:23 am GMT

Create a Calendar in HTML and CSS

A calendar widget is the most important component for events-related websites. It helps users to see schedule or event information for a specific day or date. Besides this, a calendar is also used in the date picker, event scheduler, or general-purpose calendar widget projects. If you are working on such a project in which you need to implement a calendar widget, you are in the right place. In our last tutorial we learned Create Custom Scroll Bar Using CSS

In this tutorial, Im going to explain how to create a calendar in HTML, CSS, and JavaScript.

Image description
You definitely need a calendar that you can design according to your needs. So, Ill focus on the customization as well as creating the calendar widget by adding its assets to your project. Basically, this calendar widget doesnt require a library or plugin as its purely written in JavaScript. Anyhow, it uses Font Awesome CSS for calendar navigation keys.

Before getting started with HTML, I would suggest you check out the demo page given below to see how the calendar works. You can highly customize its layout, current date, disabled date, and next/prev buttons navigation as you want.

The HTML Structure

In HTML, load the Reset CSS in order to clear the default browsers formatting of HTML elements. Similarly, load Roboto fonts and Font Awesome CSS (for icons) by adding the following CDN links into the head tag of your webpage.

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />

We need to have a div element in which the calendar will be rendered dynamically. So, create a div element with a class name "softcard", place next/prev buttons, and a div element with an id "soft-btn" inside it.

<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" /><div class="softcard">  <div class="calendar-bar">    <button class="prev soft-btn"><i class="fas fa-chevron-left"></i></button>    <div class="current-month"></div>    <button class="next soft-btn"><i class="fas fa-chevron-right"></i></button>  </div>  <div class="calendar">    <div class="weekdays-name">      <div class="days-name">Sa</div>      <div class="days-name">Su</div>      <div class="days-name">Mo</div>      <div class="days-name">Tu</div>      <div class="days-name">We</div>      <div class="days-name">Th</div>      <div class="days-name">Fr</div>    </div>    <div class="calendar-days"></div>  </div>  <div class="goto-buttons">    <button type="button" class="btn prev-year">Prev Year</button>    <button type="button" class="btn today">Today</button>    <button type="button" class="btn next-year">Next Year</button>  </div></div>

You can place the above HTML structure anywhere in your webpage/app where you want to create a calendar widget.

Create CSS Styles for Calendar

After creating the Soft Card in HTML, now its time to style the calendar layout. Therefore, select the "calendar-bar" class and define its width, background, padding, and border properties as follows. You can set the custom background color according to your choice.

<style>* {  margin: 0;  padding: 0;}body {  height: 100vh;  background: #ddd;  display: flex;  justify-content: center;  align-items: center;  font-family: "Quicksand", sans-serif;  user-select: none;}.softcard {  width: 316px;  height: fit-content;  background: -webkit-linear-gradient(to right, #f7b733, #fc4a1a);  /* Chrome 10-25, Safari 5.1-6 */  background: linear-gradient(to right, #f7b733, #fc4a1a); /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */  border-radius: 20px;  box-shadow: 0px 0px 10px #000;}.calendar-bar {  display: flex;  justify-content: space-between;  align-items: center;  padding: 20px;  padding-bottom: 15px;  border-bottom: 19px;}.calendar-bar > .current-month {  font-size: 20px;  font-weight: bold;  color: #ddd;  background:#000;  padding:5px;  border-radius:10px;}.calendar-bar > [class$="soft-btn"] {  width: 40px;  aspect-ratio: 1;  text-align: center;  line-height: 40px;  font-size: 14px;  color: #000;  background: #ddd;  border: none;  border-radius: 50%;}.weekdays-name,.calendar-days {  display: flex;  flex-wrap: wrap;  padding-inline:18px;}.weekdays-name {  padding-top: 12px;}.calendar-days {  padding-bottom: 12px;}.days-name,[class$="-day"] {  width: 40px;  height: 40px;  color: #000;  text-align: center;  line-height: 40px;  font-weight: 500;  font-size: 1rem;}.days-name {  color: #fff;  font-weight: 700;}.current-day {  background-color: #000;  color: #fff;  border-radius: 50%;  font-weight: 700;  transition: 0.5s;  cursor: pointer;}.padding-day {  color: #a5a5a5;  user-select: none;}.calendar-bar > [class$="soft-btn"]:hover,.month-day:hover,.btn:hover {  border-radius:5px;  background-color:#f8f7fa;  color:#000;  border-radius:15px;  transition: 0.1s;  cursor: pointer;}.calendar-bar > [class$="soft-btn"]:focus,.month-day:focus,.btn:focus {  border-radius:15px;  background-color: #000;  color: #ddd;}.goto-buttons {  border-top: solid 2px yellow;  padding-block: 18px;  display: flex;  justify-content: space-evenly;}.btn {  background: #eee  border: none;  border-radius: 10px;  padding: 11px 13px;  color:#000;  font-family: "Quicksand", sans-serif;  font-weight: 600;  font-size: 0.9rem;  margin-right: 1px;  box-shadow: 0px 0px 0px #000;}</style>

The JavaScript Function

Now everything is ready, finally, you only need to add the calendar JavaScript function into your project. So, add the following code between script tag before closing the body tag.

If you need to add more functionality to it you can modify the code accordingly. The purpose of each variable, object, and function is assigned, so you can easily understand what the calendar function does.

JavaScript Code:

var currentMonth = document.querySelector(".current-month");var calendarDays = document.querySelector(".calendar-days");var today = new Date();var date = new Date();currentMonth.textContent = date.toLocaleDateString("en-US", {month:'long', year:'numeric'});today.setHours(0,0,0,0);renderCalendar();function renderCalendar(){    const prevLastDay = new Date(date.getFullYear(),date.getMonth(),0).getDate();    const totalMonthDay = new Date(date.getFullYear(),date.getMonth()+1,0).getDate();    const startWeekDay = new Date(date.getFullYear(),date.getMonth(),1).getDay();    calendarDays.innerHTML = "";    let totalCalendarDay = 6 * 7;    for (let i = 0; i < totalCalendarDay; i++) {        let day = i-startWeekDay;        if(i <= startWeekDay){            // adding previous month days            calendarDays.innerHTML += `<div class='padding-day'>${prevLastDay-i}</div>`;        }else if(i <= startWeekDay+totalMonthDay){            // adding this month days            date.setDate(day);            date.setHours(0,0,0,0);                       let dayClass = date.getTime()===today.getTime() ? 'current-day' : 'month-day';            calendarDays.innerHTML += `<div class='${dayClass}'>${day}</div>`;        }else{            // adding next month days            calendarDays.innerHTML += `<div class='padding-day'>${day-totalMonthDay}</div>`;        }    }}document.querySelectorAll(".soft-btn").forEach(function (element) {    element.addEventListener("click", function () {        date = new Date(currentMonth.textContent);        date.setMonth(date.getMonth() + (element.classList.contains("prev") ? -1 : 1));        currentMonth.textContent = date.toLocaleDateString("en-US", {month:'long', year:'numeric'});        renderCalendar();    });});document.querySelectorAll(".btn").forEach(function (element) {    element.addEventListener("click", function () {        let btnClass = element.classList;        date = new Date(currentMonth.textContent);        if(btnClass.contains("today"))            date = new Date();        else if(btnClass.contains("prev-year"))            date = new Date(date.getFullYear()-1, 0, 1);        else            date = new Date(date.getFullYear()+1, 0, 1);        currentMonth.textContent = date.toLocaleDateString("en-US", {month:'long', year:'numeric'});        renderCalendar();    });});

Hopefully from this article, you have learned how to make it. If there is any difficulty, you can let me know by discussing below.
Read in detail from our official website Create a Calendar in HTML and CSS

To see DEMO

Dont forget to like and Follow to learn more amazing tutorials


Original Link: https://dev.to/softcodeon/create-a-calendar-in-html-and-css-4gg9

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To