Calendar html css javascript

Custom calendar using HTML, CSS & JavaScript

Hello Guys! Welcome to Coding Torque. In this blog, I’m going to explain to you how to make a custom calendar using HTML, CSS, and JavaScript. This will be a step-by-step guide including HTML and CSS. Let’s get started 🚀.

Let’s cover HTML Part

We use HTML to make the skeleton of a website. HTML is a markup language. Now let’s import the font awesome CDN in our HTML tag. fontawesome is a library that is used for icons in a website.

  rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA= na">crossorigin="anonymous" /> 

Now let’s import the fonts using Google Fonts API. Below is the code for Poppins Font. Paste the below code in tag.

 rel="preconnect" href="https://fonts.googleapis.com">  rel="preconnect" href="https://fonts.gstatic.com" crossorigin>  href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet"> 
 class="container">  class="calendar">  class="month">  class="fas fa-angle-left prev">  class="date">   class="fas fa-angle-right next">   class="weekdays"> Sun Mon Tue Wed Thu Fri Sat   class="days">

Источник

Calendar html css javascript

Этот виджет календаря не требует внешних библиотек, поскольку он написан исключительно на JavaScript, CSS и HTML. Из внешних источников используется только Font Awesome CSS для клавиш навигации, но при желании их тоже можно заменить на собственные.

Структура HTML

В HTML загрузите Reset CSS , чтобы очистить форматирование HTML-элементов в браузере по умолчанию. Аналогичным образом загрузите Font Awesome CSS для значков, добавив следующие ссылки CDN в тег заголовка вашей веб-страницы.

Нам нужен элемент div , в котором календарь будет отображаться динамически. Создайте элемент div с именем класса calendar-wrapper , разместите кнопки смены месяца «следующий/предыдущий» и элемент div с идентификатором divCal .

Не забудьте добавить ссылку на будущий файл .js , где будет основной функционал.

Вы можете разместить приведенную выше HTML-структуру в любом месте вашей веб-страницы/приложения, где вы хотите создать виджет календаря.

Создание стилей CSS

После создания оболочки в HTML пришло время настроить макет календаря. Выберите класс calendar-wrapper и определите его ширину, поля, отступы и свойства границы следующим образом. Вы можете установить собственный цвет фона по вашему выбору.

Функция календаря генерирует даты, расположенные в виде таблицы. Таким образом, вы можете легко настроить макет календаря, выбрав элемент таблицы. Ниже приведены стили по умолчанию, вы можете изменить их в соответствии с вашими потребностями.

Класс not-current для элемента td указывает отключенные даты в календаре. Если вы хотите скрыть эти даты, вы можете использовать свойство видимости CSS со «скрытым» значением.

Если вы хотите настроить текущую дату, вы можете выбрать today класс и определить для него стили CSS.

В календаре используется значок Font Awesome внутри кнопок. Эти кнопки навигации по календарю можно настроить, выбрав их по идентификатору. Вы можете установить собственный цвет фона, размер шрифта и значок для этих кнопок в соответствии с вашими потребностями.

#btnPrev < float: left; margin-bottom: 20px; >#btnPrev:before < content: '\f104'; font-family: FontAwesome; padding-right: 4px; >#btnNext < float: right; margin-bottom: 20px; >#btnNext:after < content: '\f105'; font-family: FontAwesome; padding-left: 4px; >#btnPrev, #btnNext

Также вы можете определить стиль наведения для кнопок «следующая/предыдущая».

#btnPrev:hover, #btnNext:hover

Добавляем JavaScript

На этом этапе мы можем перейти к главному и добавить функцию JavaScript календаря в свой проект перед закрытием тега body .

var Cal = function(divId) < //Сохраняем идентификатор div this.divId = divId; // Дни недели с понедельника this.DaysOfWeek = [ 'Пн', 'Вт', 'Ср', 'Чтв', 'Птн', 'Суб', 'Вск' ]; // Месяцы начиная с января this.Months =['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь']; //Устанавливаем текущий месяц, год var d = new Date(); this.currMonth = d.getMonth(); this.currYear = d.getFullYear(); this.currDay = d.getDate(); >; // Переход к следующему месяцу Cal.prototype.nextMonth = function() < if ( this.currMonth == 11 ) < this.currMonth = 0; this.currYear = this.currYear + 1; >else < this.currMonth = this.currMonth + 1; >this.showcurr(); >; // Переход к предыдущему месяцу Cal.prototype.previousMonth = function() < if ( this.currMonth == 0 ) < this.currMonth = 11; this.currYear = this.currYear - 1; >else < this.currMonth = this.currMonth - 1; >this.showcurr(); >; // Показать текущий месяц Cal.prototype.showcurr = function() < this.showMonth(this.currYear, this.currMonth); >; // Показать месяц (год, месяц) Cal.prototype.showMonth = function(y, m) < var d = new Date() // Первый день недели в выбранном месяце , firstDayOfMonth = new Date(y, m, 7).getDay() // Последний день выбранного месяца , lastDateOfMonth = new Date(y, m+1, 0).getDate() // Последний день предыдущего месяца , lastDayOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate(); var html = ''; // Запись выбранного месяца и года html += ''; html += ''; html += ''; // заголовок дней недели html += ''; > html += ''; // Записываем дни var i=1; do < var dow = new Date(y, m, i).getDay(); // Начать новую строку в понедельник if ( dow == 1 ) < html += ''; > // Если первый день недели не понедельник показать последние дни предыдущего месяца else if ( i == 1 ) < html += ''; var k = lastDayOfLastMonth - firstDayOfMonth+1; for(var j=0; j < firstDayOfMonth; j++) < html += ''; > // Если последний день месяца не воскресенье, показать первые дни следующего месяца else if ( i == lastDateOfMonth ) < var k=1; for(dow; dow < 7; dow++) < html += '
' + this.Months[m] + ' ' + y + '
'; k++; > > // Записываем текущий день в цикл var chk = new Date(); var chkY = chk.getFullYear(); var chkM = chk.getMonth(); if (chkY == this.currYear && chkM == this.currMonth && i == this.currDay) < html += ''; > else < html += ''; > // закрыть строку в воскресенье if ( dow == 0 ) < html += '
'; k++; > > i++; >while(i '; // Записываем HTML в div document.getElementById(this.divId).innerHTML = html; >; // При загрузке окна window.onload = function() < // Начать календарь var c = new Cal("divCal"); c.showcurr(); // Привязываем кнопки «Следующий» и «Предыдущий» getId('btnNext').onclick = function() < c.nextMonth(); >; getId('btnPrev').onclick = function() < c.previousMonth(); >; > // Получить элемент по id function getId(id)

Если вам нужно добавить больше функциональности, вы можете соответствующим образом изменить код. Назначение каждой переменной, объекта и функции прокомментировано, поэтому вы можете легко понять, что делает функция календаря.

Заключение

Ну вот мы наконец и перевернули наш календарь. Это довольно простой, но в то же время гибкий пример использования JS в веб-разработке. Виджет написан на чистом JS. При желании вы даже можете исключить из него Font Awesome CSS, чтобы убрать весь внешний код. Это никак не повлияет на функционал. Оформление можно сделать любым на усмотрение, а функционал календаря расширить, добавив собственные функции на ваше усмотрение.

Источник

How To Create Calendar Using HTML, CSS & Javascript?

Dear Coders! In this lesson, we’ll use HTML, CSS, and JavaScript to build our Own Calendar. Every day, we consult a calendar to confirm the day and date. Can you, however, conceive of a way we could create our own calendar using HTML, CSS, and JavaScript? Using HTML, CSS, and JavaScript, we will learn how to make our own calendar in this article today.

How To Create Calendar Using HTML , CSS & Javascript?

master frontend development ebook cover

Do you want to learn HTML to JavaScript? 🔥

If yes, then here is our Master Frontend: Zero to Hero eBook! 📚 In this eBook, you’ll learn complete HTML, CSS, Bootstrap, and JavaScript from beginner to advance level. 💪 It includes 450 Projects with source code.

This project is simple enough for beginners to comprehend right away if they simply read the article. You will have an understanding of how to use javascript to add style to our structure and calendar concept. Simply copy the code into your IDE if you want to save time. We advise you to create separate files for HTML, CSS, and Javascript.

Javascript is the main component of our calendar project.

Let’s now begin to structure our calendar.

Step1: Adding Some Basic HTML.

HTML stands for HyperText Markup Language. This is a markup language. Its main job is to give our project structure. We will provide our project structure by utilizing this markup language. So let’s look at our HTML code.

We have used minimum HTML code to add the basic structure to our calendar. First of all, we have added the external file link to our head section in order to add styling to our project.

The styling for our calendar will be added utilizing the div block level tag that we have now introduced. Even when viewing the project output, you will only see a blank page without any styling, thus we have inserted some placeholder text to make it clearer to you that we have added structure to our webpage.

Calendar Using Html

Now we added a basic structure to our webpage. Now using the CSS will be adding our main style to our webpage.

Step2: Adding CSS

@import url(«https://fonts.googleapis.com/css2?family=IBM+Plex+Sans:[email protected];200;300;400;500;600;700&display=swap»); :root < --calendar-bg-color: #262829; --calendar-font-color: #fff; --weekdays-border-bottom-color: #404040; --calendar-date-hover-color: #505050; --calendar-current-date-color: #1b1f21; --calendar-today-color: linear-gradient(to bottom, #03a9f4, #2196f3); --calendar-today-innerborder-color: transparent; --calendar-nextprev-bg-color: transparent; --next-prev-arrow-color: #fff; --calendar-border-radius: 16px; --calendar-prevnext-date-color: #484848; >* < padding: 0; margin: 0; >.calendar < font-family: "IBM Plex Sans", sans-serif; position: relative; max-width: 400px; /*change as per your design need */ min-width: 320px; background: var(--calendar-bg-color); color: var(--calendar-font-color); margin: 20px auto; box-sizing: border-box; overflow: hidden; font-weight: normal; border-radius: var(--calendar-border-radius); >.calendar-inner < padding: 10px 10px; >.calendar .calendar-inner .calendar-body < display: grid; grid-template-columns: repeat(7, 1fr); text-align: center; >.calendar .calendar-inner .calendar-body div < padding: 4px; min-height: 30px; line-height: 30px; border: 1px solid transparent; margin: 10px 2px 0px; >.calendar .calendar-inner .calendar-body div:nth-child(-n + 7) < border: 1px solid transparent; border-bottom: 1px solid var(--weekdays-border-bottom-color); >.calendar .calendar-inner .calendar-body div:nth-child(-n + 7):hover < border: 1px solid transparent; border-bottom: 1px solid var(--weekdays-border-bottom-color); >.calendar .calendar-inner .calendar-body div > a < color: var(--calendar-font-color); text-decoration: none; display: flex; justify-content: center; >.calendar .calendar-inner .calendar-body div:hover < border: 1px solid var(--calendar-date-hover-color); border-radius: 4px; >.calendar .calendar-inner .calendar-body div.empty-dates:hover < border: 1px solid transparent; >.calendar .calendar-inner .calendar-controls < display: grid; grid-template-columns: repeat(3, 1fr); >.calendar .calendar-inner .calendar-today-date < display: grid; text-align: center; cursor: pointer; margin: 3px 0px; background: var(--calendar-current-date-color); padding: 8px 0px; border-radius: 10px; width: 80%; margin: auto; >.calendar .calendar-inner .calendar-controls .calendar-year-month < display: flex; min-width: 100px; justify-content: space-evenly; align-items: center; >.calendar .calendar-inner .calendar-controls .calendar-next < text-align: right; >.calendar .calendar-inner .calendar-controls .calendar-year-month .calendar-year-label, .calendar .calendar-inner .calendar-controls .calendar-year-month .calendar-month-label < font-weight: 500; font-size: 20px; >.calendar .calendar-inner .calendar-body .calendar-today < background: var(--calendar-today-color); border-radius: 4px; >.calendar .calendar-inner .calendar-body .calendar-today:hover < border: 1px solid transparent; >.calendar .calendar-inner .calendar-body .calendar-today a < outline: 2px solid var(--calendar-today-innerborder-color); >.calendar .calendar-inner .calendar-controls .calendar-next a, .calendar .calendar-inner .calendar-controls .calendar-prev a < color: var(--calendar-font-color); font-family: arial, consolas, sans-serif; font-size: 26px; text-decoration: none; padding: 4px 12px; display: inline-block; background: var(--calendar-nextprev-bg-color); margin: 10px 0 10px 0; >.calendar .calendar-inner .calendar-controls .calendar-next a svg, .calendar .calendar-inner .calendar-controls .calendar-prev a svg < height: 20px; width: 20px; >.calendar .calendar-inner .calendar-controls .calendar-next a svg path, .calendar .calendar-inner .calendar-controls .calendar-prev a svg path < fill: var(--next-prev-arrow-color); >.calendar .calendar-inner .calendar-body .prev-dates, .calendar .calendar-inner .calendar-body .next-dates < color: var(--calendar-prevnext-date-color); >.calendar .calendar-inner .calendar-body .prev-dates:hover, .calendar .calendar-inner .calendar-body .next-dates:hover

We’ll utilize some simple CSS code. It will be simple for you to understand and attempt to incorporate your style, which will assist you to clarify your concepts. The CSS will be explained step by step.

Step1: First, we’ll import some Google Fonts using some Google Font Links so that we may use them later to give our project some flair.

Now using the root selector we will be defining some styling to our root element so that we can inherit our style from the root selector.

Step2: Now we will add padding and margin as “zero” to our element using the universal (*) selector.

Источник

Build a Dynamic Calendar using HTML5, CSS3 & JavaScript

Build a Dynamic Calendar using HTML5, CSS3 & JavaScript

In this tutorial, I will teach you how to make a dynamic calendar using HTML5, CSS3, and JavaScript. The full source code of the JavaScript calendar is given below.

HTML5, CSS3, JavaScript Calendar Source Code

index.html

script.js

const daysTag = document.querySelector(".days"), currentDate = document.querySelector(".current-date"), prevNextIcon = document.querySelectorAll(".icons span"); // getting new date, current year and month let date = new Date(), currYear = date.getFullYear(), currMonth = date.getMonth(); // storing full name of all months in array const months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; const renderCalendar = () => < let firstDayofMonth = new Date(currYear, currMonth, 1).getDay(), // getting first day of month lastDateofMonth = new Date(currYear, currMonth + 1, 0).getDate(), // getting last date of month lastDayofMonth = new Date(currYear, currMonth, lastDateofMonth).getDay(), // getting last day of month lastDateofLastMonth = new Date(currYear, currMonth, 0).getDate(); // getting last date of previous month let liTag = ""; for (let i = firstDayofMonth; i >0; i--) < // creating li of previous month last days liTag += ` `; >for (let i = 1; i for (let i = lastDayofMonth; i < 6; i++) < // creating li of next month first days liTag += ` ` >currentDate.innerText = `$ $`; // passing current mon and yr as currentDate text daysTag.innerHTML = liTag; > renderCalendar(); prevNextIcon.forEach(icon => < // getting prev and next icons icon.addEventListener("click", () => < // adding click event on both icons // if clicked icon is previous icon then decrement current month by 1 else increment it by 1 currMonth = icon.id === "prev" ? currMonth - 1 : currMonth + 1; if(currMonth < 0 || currMonth >11) < // if current month is less than 0 or greater than 11 // creating a new date of current year & month and pass it as date value date = new Date(currYear, currMonth); currYear = date.getFullYear(); // updating current year with new date year currMonth = date.getMonth(); // updating current month with new date month >else < date = new Date(); // pass the current date as date value >renderCalendar(); // calling renderCalendar function >); >);

style.css

/* Import Google font — Poppins */ @import url(‘https://fonts.googleapis.com/css2?family=Poppins:[email protected];500;600&display=swap’); * < margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; >body < display: flex; align-items: center; padding: 0 10px; justify-content: center; min-height: 100vh; background: #9B59B6; >.wrapper < width: 450px; background: #fff; border-radius: 10px; box-shadow: 0 15px 40px rgba(0,0,0,0.12); >.wrapper header < display: flex; align-items: center; padding: 25px 30px 10px; justify-content: space-between; >header .icons < display: flex; >header .icons span < height: 38px; width: 38px; margin: 0 1px; cursor: pointer; color: #878787; text-align: center; line-height: 38px; font-size: 1.9rem; user-select: none; border-radius: 50%; >.icons span:last-child < margin-right: -10px; >header .icons span:hover < background: #f2f2f2; >header .current-date < font-size: 1.45rem; font-weight: 500; >.calendar < padding: 20px; >.calendar ul < display: flex; flex-wrap: wrap; list-style: none; text-align: center; >.calendar .days < margin-bottom: 20px; >.calendar li < color: #333; width: calc(100% / 7); font-size: 1.07rem; >.calendar .weeks li < font-weight: 500; cursor: default; >.calendar .days li < z-index: 1; cursor: pointer; position: relative; margin-top: 30px; >.days li.inactive < color: #aaa; >.days li.active < color: #fff; >.days li::before < position: absolute; content: ""; left: 50%; top: 50%; height: 40px; width: 40px; z-index: -1; border-radius: 50%; transform: translate(-50%, -50%); >.days li.active::before < background: #9B59B6; >.days li:not(.active):hover::before

  1. How to Make a Dynamic Image Editor With Effects in HTML5, CSS3 & JavaScript
  2. Build English Dictionary App Using JavaScript HTML5 CSS3
  3. Build File Downloader From URL Using JavaScript HTML5 CSS3
  4. Build Random Song Lyrics Generator Using JavaScript HTML5 CSS3
  5. Build Random Pokemon Generator Using JavaScript, HTML5 & CSS3
  6. Create PDF Using Dynamic HTML5 Template in Python 3 Flask pdfkit
  7. Build Vorici Chromatic Calculator Using HTML5 and JavaScript
  8. Build a New Year Countdown Timer Clock in JavaScript & HTML5
  9. Create Digital Alarm Clock With Ringtone & Custom Icons in JavaScript HTML5 CSS3
  10. How to Design Old Yahoo Messenger Login/Register UI Clone in HTML5 CSS3 JavaScript
  11. How to Design Responsive Pinterest Landing & Posts Pages UI Clone in HTML5 CSS3 & JavaScript
  12. Amazon Prime Video Website Clone in HTML5 CSS3 & JavaScript
  13. How to Make WordPress Admin Login Page Clone in HTML5 & CSS3
  14. How to Design Google Search Engine Landing Page UI Clone in HTML5 & CSS3
  15. How to Make Google Translate Clone With Text to Speech in HTML5 CSS3 & JavaScript
  16. Flutter Build PDF Documents Viewer From URL Using Syncfusion
  17. Build Ping Pong Game Using OpenGL and C Programming Code
  18. Build Multiplayer Car Racing Game Using C++ Graphics Program
  19. Build React.js Express SQLite3 CRUD App Using Sequelize & Node.js
  20. Build Bitly URL Shortener Clone Using Node.js Express EJS MySQL

Источник

Читайте также:  Ошибка подключения майнкрафт java net connectexception
Оцените статью