push new items to an object from fields - javascript

actually i'm about to create a calendar with events, and i want to add new events with a form, let me explain.
i have:
let eventsArray = [
{
id: 'my event name',
date: '2021/08/23',
content: 'my events description',
},
];
result and demo:
https://jsfiddle.net/er73av8h/
Now, i want to populate this object through 3 field maybe (id, date and content), but i'm not sure on how i can do this.

I made a very simple example of what you want.
If my example works for you I will write a description of how this code works.
Example:
let eventsArray = [
{
id: 'my event name',
date: '2021/08/23',
content: 'my events description',
},
];
let wrp = document.getElementById('calendar');
function addInfoInCalendar() {
wrp.innerHTML = '';
for (const iterator of eventsArray) {
wrp.innerHTML += '<div>' + iterator.id + ' ' + iterator.date + ' ' + iterator.content + '</div>';
}
}
addInfoInCalendar();
let formWrp = document.getElementById('myForm');
let f_id = myForm.querySelectorAll('[name="id"]')[0];
let f_date = myForm.querySelectorAll('[name="date"]')[0];
let f_content = myForm.querySelectorAll('[name="content"]')[0];
let f_button = myForm.querySelector('button');
f_button.addEventListener('click', addNewInfo);
function addNewInfo() {
eventsArray.push({
id: f_id.value,
date: f_date.value,
content: f_content.value
});
addInfoInCalendar();
}
<div id="myForm">
<input type="text" name="id">
<input type="date" name="date">
<input type="text" name="content">
<button>Send</button>
</div>
<div id="calendar"></div>
Example 2:
In this example is your code! I added a few new lines at the end of the code and marked them with a comment.
let eventsArray = [
{
id: 'My Name',
date: '2021/08/23',
content: 'my events description',
source: '#',
},
];
let today = new Date(),
currentMonth = today.getMonth(),
currentYear = today.getFullYear();
// array for weeks
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
// array for month
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// structure
let structureCalendar = createElement('div', window.root, {
id: 'structureCalendar',
}),
// header
calendarHeader = createElement('header', structureCalendar, {}),
// header columns left center and right
headerLeft = createElement('div', calendarHeader, { className: 'left' }),
headerCenter = createElement('div', calendarHeader, { className: 'center' }),
headerRight = createElement('div', calendarHeader, { className: 'right' }),
// inside left column
buttonPrev = createElement('button', headerLeft, { textContent: 'Previous' }),
buttonNext = createElement('button', headerLeft, { textContent: 'Next' }),
centerTitle = createElement('h1', headerCenter, {
textContent: months[currentMonth] + ' ' + currentYear,
}),
// calendar body
calendarBody = createElement('div', structureCalendar, { id: 'calendar' }),
weekdayBody = createElement('ul', calendarBody, { id: 'weekdays' }),
daysBody = createElement('ul', calendarBody, { id: 'days' });
// init calendar
showCalendar(currentMonth, currentYear);
// map week days
weekdays.map((item, i) =>
// change to monday
today.getDay() - 0 == i
? createElement('li', weekdayBody, { className: 'today', textContent: item })
: createElement('li', weekdayBody, { textContent: item })
);
// buttons next prev
buttonPrev.onclick = () => prev();
buttonNext.onclick = () => next();
// generate calendar
function showCalendar(month, year) {
// first day - 1
let firstDay = new Date(year, month).getDay() - 1;
// clear preview content
daysBody.textContent = '';
// filing data about month and in the page via DOM.
centerTitle.textContent = months[month] + ' ' + year;
// creating all cells
let date = 1;
for (let i = 0; i < 6; i++) {
//creating individual cells, filing them up with data.
for (let j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
createElement('li', daysBody, { textContent: '' });
} else if (date > daysInMonth(month, year)) {
break;
} else {
let li = createElement('li', daysBody, {}),
info = createElement('div', li, {
className: 'info',
textContent: weekdays[j],
}),
div = createElement('div', li, { className: 'date', textContent: date });
// ----------------------------
// ----- view events
if (typeof eventsArray !== 'undefined') {
viewEvents(eventsArray, li, [year, month, date]);
}
// ----------------------------
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
li.className = 'today';
}
date++;
}
}
}
}
// view events
function viewEvents(data, where, args) {
return (
data &&
data.map((item) => {
let date = item.date.split('/'),
year = parseInt(date[0]),
month = parseInt(date[1]) - 1,
day = parseInt(date[2]);
if (year === args[0] && month === args[1] && day === args[2]) {
let event = createElement('div', where, { className: 'ev', id: item.id }),
eventDesc = createElement('div', event, { className: 'ev-desc' });
eventDesc.innerHTML = `<div class="eventFlarumCalendar">${item.content}</div>`;
event.onclick = () => alert(eventDesc.textContent);
}
})
);
}
// next month
function next() {
currentMonth = (currentMonth + 1) % 12;
currentYear = currentMonth === 11 ? currentYear + 1 : currentYear;
showCalendar(currentMonth, currentYear);
}
// previus month
function prev() {
currentMonth = currentMonth === 0 ? 11 : currentMonth - 1;
currentYear = currentMonth === 0 ? currentYear - 1 : currentYear;
showCalendar(currentMonth, currentYear);
}
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
// --- Create element
function createElement(element, where, args) {
let d = document.createElement(element);
if (args) for (const [k, v] of Object.entries(args)) d[k] = v;
where.appendChild(d);
return d;
}
/////////////////////////////////////////////////////////////
// NEW LINES
let formWrp = document.getElementById('myForm');
let f_id = myForm.querySelectorAll('[name="id"]')[0];
let f_date = myForm.querySelectorAll('[name="date"]')[0];
let f_content = myForm.querySelectorAll('[name="content"]')[0];
let f_button = myForm.querySelector('button');
f_button.addEventListener('click', addNewInfo);
function addNewInfo() {
let nfd = f_date.value.split('-').join('/');
eventsArray.push({
id: f_id.value,
date: nfd,
content: f_content.value
});
showCalendar(currentMonth, currentYear);
}
.eventFlarumCalendar {
cursor: help;
}
#structureCalendar header {
height: 4rem;
line-height: 4rem;
text-align: center;
background: #ff6200;
color: #fdfdfd;
}
#structureCalendar header .left,
#structureCalendar header .center,
#structureCalendar header .right {
width: 100%;
float: left;
}
#structureCalendar header .left h1,
#structureCalendar header .center h1,
#structureCalendar header .right h1 {
line-height: 1.8rem;
font-size: 25px;
}
#structureCalendar header .left button,
#structureCalendar header .center button,
#structureCalendar header .right button {
background-color: #ff6200;
border: 1px solid #ff6200;
color: #fdfdfd;
padding: 0.5rem 1rem;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 0 4px;
cursor: pointer;
transition: all 500ms ease;
}
.center {
background: #ff6200;
}
#structureCalendar header .left button:hover,
#structureCalendar header .center button:hover,
#structureCalendar header .right button:hover {
background-color: #ff6200;
border-color: #ff6200;
color: #fdfdfd;
transition: all 500ms ease;
}
#calendar #days,
#calendar #weekdays {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
}
#calendar #days li,
#calendar #weekdays li {
display: block;
float: left;
width: calc(100% / 7);
padding: 5px;
box-sizing: border-box;
}
#calendar #weekdays {
height: 40px;
background: #ff6200;
border-bottom: 2px solid #ff6200;
}
.contentcalflarum {
display: flow-root;
}
#calendar #weekdays li {
text-align: center;
text-transform: uppercase;
line-height: 20px;
border: none !important;
padding: 10px 6px;
color: #474747;
font-size: 13px;
font-weight: bold;
}
#calendar #weekdays .today {
background: #ff6200;
color: #fdfdfd;
}
#calendar #days li {
height: 150px;
overflow-y: auto;
background: #fdfdfd;
position: relative;
color: #ff6200;
border: 1px solid #f0f0f0;
}
#calendar #days li:hover {
background: #f0f0f0;
}
#calendar #days li .info {
position: absolute;
bottom: 2px;
right: 2px;
opacity: 0;
}
#calendar #days li .date {
text-align: center;
margin-bottom: 5px;
background: #777ffa;
color: #fdfdfd;
width: 25px;
height: 25px;
line-height: 25px;
border-radius: 50%;
float: right;
font-size: 12px;
font-weight: bold;
}
#calendar #days .today {
background: #f2f2fe;
}
#calendar #days .today:hover {
background: #c0c4fd;
}
.ev {
display: block;
background: #f2f2fe;
border: 1px solid #c0c4fd;
border-radius: 4px;
margin: 5px auto;
transition: background 500ms ease;
}
.ev:hover {
background: #777ffa;
transition: background 500ms ease;
}
.ev-desc {
padding: 0.2rem 0.5rem;
}
.ev-desc a {
text-decoration: none;
color: #ff6200;
transition: color 500ms ease;
}
.ev:hover .ev-desc a {
color: #a8adfc;
transition: color 500ms ease;
}
#media (max-width: 768px) {
#structureCalendar header {
height: auto;
text-align: center;
padding: 1rem;
}
#structureCalendar header .left,
#structureCalendar header .center,
#structureCalendar header .right {
width: 100%;
float: none;
}
#calendar #weekdays,
#calendar .null {
display: none;
}
#calendar #days li {
height: auto !important;
border: 1px solid #f0f0f0;
width: 100%;
padding: 10px;
margin-bottom: -1px;
}
#calendar #days li .info {
left: 2px;
opacity: 1;
color: #d9dbfe;
}
#calendar .date {
float: none;
}
}
<div id="myForm">
<input type="text" name="id">
<input type="date" name="date">
<input type="text" name="content">
<button>Send</button>
</div>
<div class="contentcalflarum">
<div class="calforflarum" id="root"></div>
</div>

you can write function to add event to the array
const addEvent = (id, event, content) => {
eventsArray.push({id, event, content})
}
And to access
for (let i = 0; i < eventsArray.length; i++) {
const event = eventsArray[i]
console.log(`This is id: ${event['id']}`)
console.log(`This is event: ${event['event']}`)
console.log(`This is content: ${event['content']}`)
}

You can use the current date as object property and then based on that date push your event and content. i.e:
8142021; //8 = month, 14 = date; 2021= year
let eventsArray = {
$8142021: [
{
id: 1,
name: 'my event name',
content: 'my events description',
},
{
id: 2,
name: 'my event',
content: 'my events description',
}
],
$8152021: [
{
id: 1,
name: 'my event name',
content: 'my events description',
},
{
id: 2,
name: 'my event',
content: 'my events description',
}
],
};
]

Related

Is there any other way to sort a drag and drop todo list without using the index of the items?

I'm working on a javascript to-do list where you can view all the elements on the list or you can view just the active items or the completed items.
Each of the views has its own array which I sorted out using the index of each element
but when I reorder the list on one of the views, the change is not implemented in the other views.
How do I rectify this?
const dragArea1 = document.querySelector('#task1');
const dragArea2 = document.querySelector('#task2');
const dragArea3 = document.querySelector('#task3');
const addnew = document.querySelector('[name="addnew"]')
const add = document.querySelector('[name="new"]')
const countIt = document.querySelector('#count')
var all = [];
var active = [];
var complete = [];
var lists = document.querySelectorAll('ul');
var views = document.querySelectorAll('.action .views a');
var mobileViews = document.querySelectorAll('#views a');
var list = document.querySelector('.list');
countIt.innerHTML = active.length;
addnew.addEventListener('click', () => {
var newItem
if (addnew.checked == true) {
newItem = {
val: add.value,
checked: false
}
all.push(newItem);
active.push(newItem);
window.setTimeout(() => {
addnew.checked = false;
add.value = '';
}, 300);
displayAll();
count();
}
})
list.addEventListener('click', (ev) => {
if (ev.target.tagName === 'LABEL' || ev.target.tagName === 'P' || ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
sortAllList();
if (lists[1].style.display == 'block') {
activeToComplete();
}
if (lists[2].style.display == 'block') {
completeToActive();
}
sortActive();
sortComplete();
}
if (all.length == 0) {
var htmlCode = `<em style="text-align: center; width: 100%; padding: 20px;">add a todo item</em>`;
lists[0].innerHTML = htmlCode;
}
if (active.length == 0) {
var htmlCode = `<em style="text-align: center; width: 100%; padding: 20px;">add a todo item</em>`;
lists[1].innerHTML = htmlCode;
}
if (complete.length == 0) {
var htmlCode = `<em style="text-align: center; width: 100%; padding: 20px;">complete a todo item</em>`;
lists[2].innerHTML = htmlCode;
}
// console.log(ev.target.tagName);
})
function count() {
// to keep count of active items
countIt.innerHTML = active.length;
}
views[0].classList.add('view')
mobileViews[0].classList.add('view')
function displayAll() {
sortActive();
sortComplete();
var htmlCode = "";
if (all.length !== 0) {
for (let i = 0; i < all.length; i++) {
htmlCode += `
<li draggable="true">
<div class="check">
<input type="checkbox" name="listItem" id="item${i}">
<label for="item${i}"></label>
</div>
<p class="itemdesc">${all[i].val}</p>
<span onclick="del(${i})">╳</span>
</li>
`
}
lists[0].innerHTML = htmlCode;
}
lists[0].style.display = 'block';
lists[1].style.display = 'none';
lists[2].style.display = 'none';
views[0].classList.add('view')
views[1].classList.remove('view')
views[2].classList.remove('view')
mobileViews[0].classList.add('view')
mobileViews[1].classList.remove('view')
mobileViews[2].classList.remove('view')
count()
keepChecked();
}
function sortActive() {
// to add active items to the active array
var fit
fit = all.filter(el => el.checked == false)
active = fit
count();
}
function sortComplete() {
//to add completed items to the complete array
var com
com = all.filter(el => el.checked == true)
complete = com
// console.log('complete', complete);
}
function sortAllList() {
// to sort the items into active and completed
const items = document.querySelectorAll('#task1 li');
for (let i = 0; i < all.length; i++) {
if (items[i].classList.contains('checked') == true) {
all[i].checked = true
} else {
all[i].checked = false
}
}
}
function activeToComplete() {
let newA
const items = document.querySelectorAll('#task2 li')
for (let i = 0; i < active.length; i++) {
if (items[i].classList.contains('checked') == true) {
active[i].checked = true;
// active.splice(i,1);
// console.log(active.splice());
} else {
active[i].checked = false
}
}
newA = active.filter(el => el.checked !== true)
console.log(newA);
active = newA;
}
function keepChecked() {
// to keep the completed items checked afetr changing views
const allItems = document.querySelectorAll('#task1 li');
for (let i = 0; i < all.length; i++) {
if (all[i].checked == true) {
allItems[i].classList.add('checked')
}
}
}
function completeToActive() {
const items = document.querySelectorAll('#task3 li')
for (let i = 0; i < complete.length; i++) {
if (items[i].classList.contains('checked') == true) {
complete[i].checked = true;
} else {
complete[i].checked = false
complete.splice(i, 1);
console.log(complete.splice());
}
}
}
function displayActive() {
sortAllList();
sortActive();
var htmlCode = "";
if (active.length !== 0) {
for (let i = 0; i < active.length; i++) {
htmlCode += `
<li draggable="true">
<div class="check">
<input type="checkbox" name="listItem" id="item${i}">
<label for="item${i}"></label>
</div>
<p class="itemdesc">${active[i].val}</p>
<span onclick="del(${i})">╳</span>
</li>
`
}
lists[1].innerHTML = htmlCode;
}
lists[1].style.display = 'block';
lists[0].style.display = 'none';
lists[2].style.display = 'none';
views[1].classList.add('view')
views[0].classList.remove('view')
views[2].classList.remove('view')
mobileViews[1].classList.add('view')
mobileViews[0].classList.remove('view')
mobileViews[2].classList.remove('view')
count()
}
function displayCompleted() {
let unique = [...new Set(complete)]
// console.log(unique[0].val);
var htmlCode = "";
if (unique.length !== 0) {
for (let i = 0; i < unique.length; i++) {
htmlCode += `
<li draggable="true" class="checked">
<div class="check">
<input type="checkbox" name="listItem" id="item${i}">
<label for="item${i}"></label>
</div>
<p class="itemdesc">${unique[i].val}</p>
<span onclick="del(${i})">╳</span>
</li>
`
}
lists[2].innerHTML = htmlCode;
}
lists[2].style.display = 'block';
lists[1].style.display = 'none';
lists[0].style.display = 'none';
views[2].classList.add('view')
views[0].classList.remove('view')
views[1].classList.remove('view')
mobileViews[2].classList.add('view')
mobileViews[1].classList.remove('view')
mobileViews[0].classList.remove('view')
count()
}
function clearComplete() {
var htmlCode = `<em style="text-align: center; width: 100%; padding: 20px;">complete a todo item</em>`;
complete = [];
lists[2].innerHTML = htmlCode;
}
function del(theIndex) {
let i = theIndex;
if (lists[0].style.display == 'block') {
all.splice(i, 1);
displayAll();
}
if (lists[1].style.display == 'block') {
active.splice(i, 1);
let removeFromAll = all.find(el => {
el == active.splice()
})
all.splice(removeFromAll, 1);
displayActive();
}
if (lists[2].style.display == 'block') {
complete.splice(i, 1);
let removeFromAll = all.find(el => {
el == complete.splice()
})
all.splice(removeFromAll, 1);
displayCompleted();
}
sortActive();
sortComplete();
}
new Sortable(dragArea1, {
animation: 350
})
new Sortable(dragArea2, {
animation: 350
})
new Sortable(dragArea3, {
animation: 350
})
:root {
--blue: hsl(220, 98%, 61%);
/* vd -> Very Drak */
--vdblue: hsl(235, 21%, 11%);
--vdDesaturatedblue: hsl(235, 24%, 19%);
--lightgrayblue: hsl(234, 39%, 85%);
--lightgrayblueh: hsl(236, 33%, 92%);
--darkgrayblue: hsl(234, 11%, 52%);
--vdGrayishblueh: hsl(233, 14%, 35%);
--vdGrayishblue: hsl(237, 14%, 26%);
--checkbg: linear-gradient(rgba(87, 221, 255, .7), rgba(192, 88, 243, .7));
--font: 'Josefin Sans', sans-serif;
font-size: 18px;
}
* {
padding: 0;
margin: 0;
font-family: var(--font);
/* font-weight: 700; */
}
*,
*::after,
*::before {
box-sizing: border-box;
}
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
border: none;
-webkit-text-fill-color: white;
background-color: transparent !important;
-webkit-box-shadow: 0 0 0px 1000px #00000000 inset;
transition: background-color 5000s ease-in-out 0s;
}
input:focus, input:active, input:visited, textarea:focus, textarea:active, textarea:visited{
background-color: transparent;
border: none;
outline: none;
}
a, em, span{
display: inline-block;
cursor: pointer;
}
a{
text-decoration: none;
display: inline-block;
}
header, main, footer{
width: 100%;
max-width: 30rem;
padding: 10px;
}
main {
display: flex;
flex-direction: column;
gap: 30px;
align-items: center;
}
main #new,
li {
display: flex;
align-items: center;
gap: 20px;
padding: 1rem;
width: 100%;
}
main section,
main #views {
width: 100%;
}
main section,
main #new,
main #views {
border-radius: 5px;
}
main .list {
min-height: 2.5rem;
max-height: 20rem;
/* height: 10rem; */
position: relative;
overflow-y: auto;
}
main .list ul {
/* position: absolute; */
/* top: 20px; */
width: 100%;
display: none;
}
main .list ul:nth-child(1) {
display: block;
}
main #new input[name="new"] {
padding: 10px;
height: inherit;
}
input {
background-color: transparent;
width: calc(100% - 70px);
border: none;
font-size: 1rem;
}
li {
justify-content: flex-start;
}
li .check {
position: relative;
}
main #new .check input,
li .check input {
display: none;
}
main #new .check label,
li .check label {
width: 30px;
height: 30px;
border-radius: 30px;
display: inline-block;
}
main #new .check input:checked~label,
li.checked .check label {
background-image: var(--checkbg), url(images/icon-check.svg);
background-position: center center;
background-repeat: no-repeat;
}
li p {
width: 85%;
}
li.checked label {
background-color: #66666696;
}
li.checked p {
text-decoration: line-through;
}
li span {
/* justify-self: flex-end; */
display: none;
}
li:hover span {
display: flex;
}
main .action {
display: flex;
justify-content: space-between;
/* gap: 2rem; */
padding: 1.1rem;
font-size: .8rem;
}
.views a,
#views a {
font-weight: 700;
}
.action a.view {
color: var(--blue);
}
main #views {
padding: .8rem;
text-align: center;
font-size: .8rem;
display: none;
}
#views a.view {
color: var(--blue);
}
main #views+p {
font-size: .7rem;
}
li,
em {
border-bottom: 1px solid var(--darkgrayblue);
}
li,
li p,
main .action a:hover {
color: var(--lightgrayblue);
}
a,
em,
li.checked p,
p,
span,
input,
li span {
color: var(--darkgrayblue);
}
header img {
content: url("images/icon-sun.svg");
}
main #new {
background-color: var(--vdDesaturatedblue);
}
main #new .check label,
li .check label {
border: 1px solid var(--vdGrayishblue);
}
main #new .check label:hover,
li .check label:hover {
border: 1px solid var(--vdGrayishblue);
}
main section,
main #views {
background-color: var(--vdDesaturatedblue);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
<main role="main">
<div id="new">
<div class="check">
<input type="checkbox" name="addnew" id="addnew">
<label for="addnew"></label>
</div>
<input type="text" name="new" placeholder="Create a new todo...">
</div>
<section>
<div class="list">
<ul id="task1">
<em style="text-align: center; width: 100%; padding: 20px;">add a todo item</em>
</ul>
<ul id="task2">
<em style="text-align: center; width: 100%; padding: 20px;">add a todo item</em>
</ul>
<ul id="task3">
<em draggable="true" style="text-align: center; width: 100%; padding: 20px;">complete a todo item</em>
</ul>
</div>
<div class="action">
<p>
<span id="count"></span> items left
</p>
<div class="views">
All
Active
Completed
</div>
Clear Completed
</div>
</section>
<div id="views">
All
Active
Completed
</div>
<p>Drag and drop to reorder list</p>
</main>

element.innerHTML is not a function and option with an object value

Hi I'm trying to do the following in javascript, basically, I have an input that I will get the input text from an array, and I need each option to have an object as a value so I can use some attributes of my object
const data = [
{
name: "SIMPLES NACIONAL – MEI",
funcionarioIncrease: 49.99,
socioIncrease: 0,
FATURAMENTO: [
{
name: "ATÉ 30.000,00",
value: 49.99,
},
{
name: "De 30.001,00 a 50.000,00 ",
value: 99.99,
},
],
},
{
name: "SIMPLES NACIONAL – SERVIÇOS",
funcionarioIncrease: 25,
socioIncrease: 25,
FATURAMENTO: [
{
name: "ATÉ 30.000,00",
value: 149.99,
},
{
name: "De 30.001,00 a 50.000,00 ",
value: 199.99,
},
],
},
];
const Modes = () => {
if (data instanceof Array) {
return data.map((value) => {
return {
name: value.name,
funcionarioIncrease: value.funcionarioIncrease,
socioIncrease: value.socioIncrease,
faturamento: value.FATURAMENTO,
};
});
} else {
return null;
}
};
let results = function () {
const modes = Modes();
let selectHeader = document.querySelectorAll(".select__header");
let selectItem = document.querySelectorAll(".select__item");
modes.map((value) => {
let element = document.createElement("div");
element.classList.add("select__item");
element.innerHTML(value.name);
});
selectHeader.forEach((item) => {
item.addEventListener("click", selectToggle);
});
selectItem.forEach((item) => {
item.addEventListener("click", selectChoose);
});
function selectToggle() {
this.parentElement.classList.toggle("is-active");
}
function selectChoose() {
let text = this.innerText,
select = this.closest(".select"),
currentText = select.querySelector(".select__current");
currentText.innerText = text;
select.classList.remove("is-active");
}
};
results();
.select {
position: relative;
width: 100%;
}
.select.is-active .select__body {
display: block;
}
.select__header {
border: 1px solid #ccc;
cursor: pointer;
display: flex;
}
.select__current {
font-size: 18px;
line-height: 24px;
padding: 8px;
}
.select__icon {
align-items: center;
display: flex;
flex-shrink: 0;
justify-content: center;
height: 40px;
margin-left: auto;
text-align: center;
width: 40px;
}
.select__body {
border: 1px solid #cccccc;
border-top: 0;
display: none;
left: 0;
position: absolute;
right: 0;
top: 100%;
}
.select__item {
cursor: pointer;
font-size: 16px;
line-height: 24px;
padding: 8px;
}
.select__item:hover {
background-color: #f2f2f2;
}
<div class="service_mode flex">
<div class="select is-active">
<div class="select__header">
<span class="select__current">Value 1</span>
<div class="select__icon">×</div>
</div>
<div class="select__body"></div>
</div>
</div>
for some reason, I am not able to map my array and add its inner HTML as the attribute name of my object and I am also not finding a way to link the option to that object.
As it says element.innerHTML is not a function. Instead of element.innerHTML(value.name);, write element.innerHTML = value.name;
So your code looks like:
modes.map((value) => {
let element = document.createElement("div");
element.classList.add("select__item");
element.innerHTML = value.name;
});
Try this below:
element.innerHTML = value.name;

Call function destroyed callback in last call

I have function, which create popup similar as alert, confirm or prompt. Problem occurs when is called new popup (any type), then is destroyed callback in first call (prompt value)
PoppyPopup.prompt('Type your name', 'User control', {}, function(value) {
PoppyPopup.alert('Welcome ' + value); //<-- value is id of second popup
});
PoppyPopup.alert('Hi, this is a PopUp!', 'With title!');
DEMO: https://jsfiddle.net/yojz8sb3/
Edit: When is call one time, it's OK, I really dont know where is problem.
Well, the short answer is because PoppyPopup isn't designed to handle having more than one popup open at a time.
popupType is shared between all popups so when you open the alert popup it sets popupType to ALERT and so when the prompt popup's accept callback is called it's handled as if it's an ALERT type popup.
One (fairly hacky) solution is to remove var popupType = null; and instead pass popupType to the Popup constructor as a 4th argument. Then you can change
PoppyPopup.accept(basePopup.id, options);
to
PoppyPopup.accept(basePopup.id, options, popupType);
in Popup function.
And change
accept: function(popupId, options) {
to
accept: function(popupId, options, popupType) {
that way the popup type is associated with the popup instance instead of being shared among all popups.
Here is a working example: https://jsfiddle.net/0xpz7f9L/
However my answer above doesn't fix the issue that clicking the accept button appears to close a random popup (obviously not ideal). I'd recommend rewriting the whole thing to simplify it and make it easier to read/understand. Also this sort of thing traditionally uses promises instead of callbacks.
Here is how I would rewrite it:
const PoppyPopup = (function() {
let nextPopupId = 0;
return {
alert: function(message, title, options) {
const realOptions = buildOptionsFrom(options);
const popupElem = buildPopupElem(title, message, realOptions, false, false);
const promise = new Promise(resolve => {
popupElem.querySelector('.accept').onclick = resolve;
});
promise.finally(() => close(popupElem, realOptions.removeWhenClosed));
document.querySelector('body').appendChild(popupElem);
return promise;
},
confirm: function(message, title, options) {
const realOptions = buildOptionsFrom(options);
const popupElem = buildPopupElem(title, message, realOptions, false, true);
const promise = new Promise((resolve, reject) => {
popupElem.querySelector('.accept').onclick = resolve;
popupElem.querySelector('.cancel').onclick = reject;
});
promise.finally(() => close(popupElem, realOptions.removeWhenClosed));
document.querySelector('body').appendChild(popupElem);
return promise;
},
prompt: function(message, title, options) {
const realOptions = buildOptionsFrom(options);
const popupElem = buildPopupElem(title, message, realOptions, true, true);
const promise = new Promise((resolve, reject) => {
popupElem.querySelector('.accept').onclick = () => resolve(popupElem.querySelector('input').value);
popupElem.querySelector('.cancel').onclick = reject;
});
promise.finally(() => close(popupElem, realOptions.removeWhenClosed));
document.querySelector('body').appendChild(popupElem);
return promise;
}
};
function close(popupElem, removeWhenClosed) {
popupElem.classList.remove('show');
popupElem.addEventListener('transitionend', function(e) {
if (e.propertyName === 'opacity' && removeWhenClosed) {
popupElem.parentNode.removeChild(popupElem);
}
});
}
function buildOptionsFrom(options) {
return Object.assign({
showBackground: true,
removeWhenClosed: true,
width: '400px'
}, options || {});
}
function buildPopupElem(title, message, options, provideInput, provideCancel) {
const basePopupDiv = document.createElement("DIV");
basePopupDiv.className = "poppy-popup show";
basePopupDiv.id = nextPopupId++;
if (options.showBackground) {
const backgroundDiv = document.createElement("DIV");
backgroundDiv.className = "poppy-popup-background";
basePopupDiv.appendChild(backgroundDiv);
}
const containerDiv = document.createElement("DIV");
containerDiv.className = "poppy-popup-container";
containerDiv.style.width = options.width;
containerDiv.style.height = options.height;
if (title) {
const headerTitleDiv = document.createElement("DIV");
headerTitleDiv.className = "poppy-popup-title-text";
headerTitleDiv.innerHTML = title;
const headerDiv = document.createElement("DIV");
headerDiv.className = "poppy-popup-header";
headerDiv.appendChild(headerTitleDiv);
containerDiv.appendChild(headerDiv);
}
const contentDiv = document.createElement("DIV");
contentDiv.className = "poppy-popup-content";
contentDiv.innerHTML = message;
if (provideInput) {
const input = document.createElement("INPUT");
input.type = "text";
contentDiv.appendChild(input);
}
const acceptLink = document.createElement("A");
acceptLink.className = 'accept';
acceptLink.href = "#";
acceptLink.innerHTML = "<i class='material-icons'>done</i> OK";
const acceptSpan = document.createElement("SPAN");
acceptSpan.className = "poppy-popup-accept";
acceptSpan.appendChild(acceptLink);
const buttonsDiv = document.createElement("DIV");
buttonsDiv.className = "poppy-popup-buttons";
buttonsDiv.appendChild(acceptSpan);
if (provideCancel) {
const cancelLink = document.createElement("A");
cancelLink.className = "cancel";
cancelLink.href = "#";
cancelLink.innerHTML = "<i class='material-icons'>close</i> Cancel";
const cancelSpan = document.createElement("SPAN");
cancelSpan.className = "poppy-popup-cancel";
cancelSpan.appendChild(cancelLink);
buttonsDiv.appendChild(cancelSpan);
}
containerDiv.appendChild(contentDiv);
containerDiv.appendChild(buttonsDiv);
basePopupDiv.appendChild(containerDiv);
return basePopupDiv;
} //end of buildPopupElem()
})();
PoppyPopup.prompt('Type your name', 'User control').then(value => {
PoppyPopup.alert('Welcome ' + value).then(() => {
PoppyPopup.confirm('And just for completeness, confirm?')
.then(() => alert('accepted'), () => alert('rejected'));
});
});
PoppyPopup.alert('Hi, this is a PopUp!', 'With title!');
*, *:before, *:after {
box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
font-family: 'Roboto', sans-serif;
font-size: 16px;
background-color: #eeeeee; }
.poppy-popup {
position: fixed;
top: 0;
left: 0;
z-index: 1000;
width: 100vw;
height: 100vh;
display: -ms-flexbox;
display: flex;
-ms-flex-pack: center;
justify-content: center;
-ms-flex-align: center;
align-items: center;
font-size: 16px;
opacity: 0;
transition: opacity .3s; }
.poppy-popup.show {
opacity: 1; }
.poppy-popup > .poppy-popup-background {
position: fixed;
top: 0;
left: 0;
z-index: 1010;
background-color: rgba(0, 0, 0, 0.5);
width: 100%;
height: 100%; }
.poppy-popup > .poppy-popup-container {
max-width: 90%;
max-height: 90%;
width: 100%;
position: relative;
z-index: 1020;
border-radius: 3px;
box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.3); }
.poppy-popup > .poppy-popup-container > .poppy-popup-header {
background-color: #FFFFFF;
color: #222222;
height: 50px;
width: 100%;
position: relative;
border-top-left-radius: 3px;
border-top-right-radius: 3px; }
.poppy-popup > .poppy-popup-container > .poppy-popup-header > .poppy-popup-title-text {
width: 100%;
max-height: 50px;
font-size: 1.5em;
text-align: center;
line-height: 50px;
text-overflow: ellipsis;
font-weight: bold;
overflow: hidden;
white-space: nowrap; }
.poppy-popup > .poppy-popup-container > .poppy-popup-content {
background-color: #FFFFFF;
width: 100%;
padding: 10px 20px;
border-left: 1px solid #DDDDDD;
border-right: 1px solid #DDDDDD;
overflow: auto; }
.poppy-popup > .poppy-popup-container > .poppy-popup-content > input[type="text"] {
background-color: transparent;
border-width: 0;
border-bottom: 2px solid #CCCCCC;
outline: none;
font-size: 1.3em;
width: 100%;
margin-top: 20px;
padding: 5px;
box-shadow: none;
transition: border-bottom .2s; }
.poppy-popup > .poppy-popup-container > .poppy-popup-content > input[type="text"]:focus {
border-bottom: 2px solid #2088AD; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons {
width: 100%;
height: 50px;
padding: 0 10px;
background-color: #FFFFFF;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
overflow: hidden; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel {
width: 120px;
display: block;
float: right;
color: #2088AD; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a {
display: block;
color: inherit;
text-decoration: none;
text-align: center;
padding: 10px 0;
border-radius: 3px;
transition: background-color .2s, box-shadow .1s; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a:active, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a:active {
box-shadow: inset 0 0 5px 1px rgba(0, 0, 0, 0.3); }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a > i, .poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a > i {
vertical-align: middle;
margin-top: -3px; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept {
right: 0;
color: #2088AD; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-accept > a:hover {
background-color: rgba(0, 0, 0, 0.1); }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel {
left: 0;
color: #2088AD; }
.poppy-popup > .poppy-popup-container > .poppy-popup-buttons > .poppy-popup-cancel > a:hover {
background-color: rgba(0, 0, 0, 0.1); }
Note: The css is unchanged.

javascript function causing postback on asp.net

This following javascript is causing an unwanted postback on asp.net webform codebehind:
mini_cal.on("click, focusin", ".a-date", function(){
if(!$(this).hasClass('blurred'))
showEvent($(this).data('event'));
});`
It's from a calendar control and the function is called when you click on a date. Adding e.preventDefault() stops the postback but then showEvent() is not called. On a plain html page everything works fine, but I need this on an aspx page cause I need to pull the events from db, server side. I hope someone could come up with a solution, since the author himself does not seem to be able to come up with one.
Ok, here's the aspx page:
<%# Page Language="VB" AutoEventWireup="false" CodeFile="caltest.aspx.vb" Inherits="caltest" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="css/mini-event-calendar.css" />
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="js/mini-event-calendar.js?v=7"></script>
<script>
var db_events = [
{
title: "Board members meeting.",
date: 1532381440036,
link: "events.com/ev2"
},
{
title: "Delaware branch opening.",
date: 1532467961534,
link: "events.com/ev1"
},
{
title: "An important event.",
date: 1532554405128,
link: "events.com/ev1"
}
];
$(document).ready(function () {
$("#calendar").MEC({
calendar_link: "example.com/myCalendar",
events: db_events
});
//if you don't have events, use
// $("#calendar2").MEC();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>With events...</h3>
<div id="calendar" runat="server" style="width: 30%;margin-right:auto;margin-left:auto;"></div> <br>
</div>
</form>
</body>
</html>
mini-event-calendar.js
(function( $ ) {
var calenderTpl = '<div id="calTitle"><button class="month-mover prev"><svg fill="#FFFFFF" height="30" viewBox="0 0 24 24" width="30" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button><div id="monthYear"></div><button class="month-mover next"><svg fill="#FFFFFF" height="30" viewBox="0 0 24 24" width="30" xmlns="http://www.w3.org/2000/svg"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/><path d="M0 0h24v24H0z" fill="none"/></svg></button></div><div><div id="calThead"><div>S</div><div>M</div><div>T</div><div>W</div><div>T</div><div>F</div><div>S</div></div><div id="calTbody"></div></div><div id="calTFooter"><h3 id="eventTitle">No events today.</h3>ALL EVENTS</div>';
var short_months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul","Aug", "Sep", "Oct", "Nov", "Dec"];
var today = new Date();
var cur_month = today.getMonth();
var cur_year = today.getFullYear();
$.fn.miniEventCalendar = $.fn.MEC = function(options) {
var settings = $.extend({
calendar_link : "",
events: []
}, options );
var mini_cal = this;
mini_cal.addClass('mini-cal').html(calenderTpl);
var tbody = mini_cal.find("#calTbody");
var cal_title = mini_cal.find("#monthYear");
var cal_footer = mini_cal.find("#calTFooter");
var event_title = mini_cal.find("#eventTitle");
var events_link = mini_cal.find("#calLink");
cal_title.text("Feb 2018");
event_title.text("No events today.");
events_link.text("ALL EVENTS");
events_link.attr("href", settings.calendar_link);
if(!settings.calendar_link.length && !settings.events.length)
cal_footer.css("display", "none");
mini_cal.find(".month-mover").each(function(){
var mover = $(this);
mover.bind("click", function(){
if(mover.hasClass("next"))
viewNextMonth();
else
viewPrevMonth();
});
});
mini_cal.on("click, focusin", ".a-date", function(){
if(!$(this).hasClass('blurred'))
showEvent($(this).data('event'));
});
function populateCalendar(month, year) {
tbody.html("");
cal_title.text(short_months[month] + " " + year);
cur_month = month;
cur_year = year;
var ldate = new Date(year, month);
var dt = new Date(ldate);
if(ldate.getDate() === 1 && dt.getDay() != 1)
tbody.append(last_prev_month_days(dt.getDay()));
while (ldate.getMonth() === month) {
dt = new Date(ldate);
var isToday = areSameDate(ldate, new Date());
var event = null;
var event_index = settings.events.findIndex(function(ev) {
return areSameDate(dt, new Date(ev.date));
});
if(event_index != -1){
event = settings.events[event_index];
if(isToday)
showEvent(event);
}
tbody.append(date_tpl(false, ldate.getDate(), isToday, event));
ldate.setDate(ldate.getDate() + 1);
var buffer_days = 43 - mini_cal.find(".a-date").length;
if(ldate.getMonth() != month)
for (var i = 1; i < buffer_days; i++)
tbody.append(date_tpl(true, i));
}
}
function last_prev_month_days(day){
if(cur_month > 0){
var month_idx = cur_month - 1;
var year_idx = cur_year;
}else{
if(cur_month < 11){
var month_idx = 0;
var year_idx = cur_year + 1;
}else{
var month_idx = 11;
var year_idx = cur_year - 1;
}
}
var prev_month = getMonthDays(month_idx, year_idx);
var last_days = "";
for (var i = day; i > 0; i--)
last_days += date_tpl(true, prev_month[ prev_month.length - i]);
return last_days;
}
function date_tpl(blurred, date, is_today, event){
var tpl = "<div class='a-date blurred'><span>"+date+"</span></div>";
if(!blurred){
var cls = is_today ? "current " : "";
cls += event && event !== null ? "event " : "";
var tpl ="<button class='a-date "+cls+"' data-event='"+JSON.stringify(event)+"'><span>"+date+"</span></button>";
}
return tpl;
}
function showEvent(event){
if(event && event !== null && event !== undefined){
event_title.text(event.title);
events_link.text("VIEW EVENT");
events_link.attr("href", event.link);
}else{
event_title.text("No events on this day.");
events_link.text("ALL EVENTS");
events_link.attr("href", settings.calendar_link);
}
}
function viewNextMonth(){
var next_month = cur_month < 11 ? cur_month + 1 : 0;
var next_year = cur_month < 11 ? cur_year : cur_year + 1;
populateCalendar(next_month, next_year);
}
function viewPrevMonth(){
var prev_month = cur_month > 0 ? cur_month - 1 : 11;
var prev_year = cur_month > 0 ? cur_year : cur_year - 1;
populateCalendar(prev_month, prev_year);
}
function areSameDate(d1, d2) {
return d1.getFullYear() == d2.getFullYear()
&& d1.getMonth() == d2.getMonth()
&& d1.getDate() == d2.getDate();
}
function getMonthDays(month, year) {
var date = new Date(year, month, 1);
var days = [];
while (date.getMonth() === month) {
days.push(date.getDate());
date.setDate(date.getDate() + 1);
}
return days;
}
populateCalendar(cur_month, cur_year);
return mini_cal;
};
}( jQuery ));
mini-event-calendar.css
.mini-cal{
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
font-family: Verdana, sans-serif;
padding-bottom: 1.2em;
background: #22252e;
color: #fff;
}
#calTitle{
display: flex;
justify-content: space-between;
-ms-align-items: center;
align-items: center;
font-size: 1.12em;
text-align: center;
padding: 0.4em 1em;
padding-top: 0.8em;
}
#calTitle button{
outline: none;
display: block;
border: 0.1em solid #ddd;
border: none;
padding: 0;
width: 40px;
height: 40px;
line-height: 60px;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.1);
}
#calTitle button svg{
width: 30px;
height: 30px;
}
#calTitle button:hover{
background: rgba(255,255,255,0.1);
}
#calThead, #calTbody{
display: flex;
flex-wrap: wrap;
padding: 0.1em;
}
#calThead{
color: #fff;
margin-top: 0.4em;
align-items: center;
text-align: center;
font-size: 0.88em;
}
#calThead > div, #calTbody .a-date{
box-sizing: border-box;
flex: 1;
min-width: calc(100% / 7);
max-width: calc(100% / 7);
width: calc(100% / 7);
text-align: center;
padding: 0;
}
#calThead > div{
font-size: 1.1em;
padding: 0.2em 0.2em;
}
#calTbody{
color: #ddd;
}
#calTbody .a-date > span{
display: block;
font-size: 1em;
}
#calTbody .a-date{
cursor: default;
padding: 0;
position: relative;
background-color: transparent;
color: inherit;
padding: 1em;
border: 0.1em solid transparent;
outline: none;
font-size: 0.9em;
}
#calTbody .a-date.blurred{
opacity: 0.5;
pointer-events: none;
}
#calTbody .a-date.event:before{
content: '';
position: absolute;
top: 0.2em;
right: 0;
left: 0;
margin: auto;
background-color: #fffc23;
width: 0.3em;
height: 0.3em;
border-radius: 50%;
}
#calTbody .a-date.current{
border-color: #fffc23;
outline: none;
outline: 0;
}
#calTbody .a-date.current.event{
background-color: #fffc23;
color: #000;
}
#calTbody .a-date:focus,
#calTbody .a-date:active{
background: #3f4042;
}
#calTFooter{
display: flex;
justify-content: space-between;
-ms-align-items: center;
align-items: center;
font-size: 1.1em;
padding: 0 1em;
margin-top: 0.5em;
}
#calTFooter #calLink{
font-size: 0.8em;
display: inline-block;
padding: 0.6em 0.8em;
flex-shrink: 0;
text-decoration: none;
color: #fffc23;
}
#calTFooter #calLink:hover{
background-color: #555;
}
#calTFooter #eventTitle{
margin: 0;
margin-right: 0.1em;
font-weight: normal;
font-size: 0.95em;
white-space: nowrap;
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}

highlight a current date

I am beginner for programming. I got a code from online and I am modifying to get hands on js, jquery, jsp. What I am trying to get is I need to highlight a today's date. I tried many times but could not succeeded. Any help will be greatly appreciated.
$(document).ready(function () {
var Calendar = function(calen) {
//Store div id
this.divId = calen.ParentID;
// Days of week, starting on Sunday
this.DaysOfWeek = calen.DaysOfWeek;
// Months, stating on January
this.Months = calen.Months;
// Set the current month, year
var d = new Date();
this.CurrentMonth = d.getMonth();
this.CurrentYear = d.getFullYear();
var f=calen.Format;
//this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';
if(typeof(f) == 'string') {
this.f = f.charAt(0).toUpperCase();
} else {
this.f = 'M';
}
};
// Goes to next month
Calendar.prototype.nextMonth = function() {
if ( this.CurrentMonth == 11 ) {
this.CurrentMonth = 0;
this.CurrentYear++;
} else {
console.log("this.CurrentMonth == ", this.CurrentMonth);
this.CurrentMonth++;
}
this.showCurrent();
};
// Goes to previous month
Calendar.prototype.previousMonth = function() {
if ( this.CurrentMonth == 0 ) {
this.CurrentMonth = 11;
this.CurrentYear--;
} else {
this.CurrentMonth--;
}
this.showCurrent();
};
//
Calendar.prototype.previousYear = function() {
this.CurrentYear--;
this.showCurrent();
}
Calendar.prototype.nextYear = function() {
this.CurrentYear++;
this.showCurrent();
}
// Show current month
Calendar.prototype.showCurrent = function() {
this.Calendar(this.CurrentYear, this.CurrentMonth);
};
// Show month (year, month)
Calendar.prototype.Calendar = function(y,m,n) {
typeof(y) == 'number' ? this.CurrentYear = y : null;
typeof(y) == 'number' ? this.CurrentMonth = m : null;
typeof(y) == 'number' ? this.CurrDate = n : null;
// 1st day of the selected month
var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();
// Last date of the selected month
var lastDateOfCurrentMonth = new Date(y, m+1, 0).getDate();
// Last day of the previous month
var lastDateOfLastMonth = m == 0 ? new Date(y-1, 11, 0).getDate() : new Date(y, m, 0).getDate();
// Write selected month and year. This HTML goes into <div id="year"></div>
//var yearhtml = '<span class="yearspan">' + y + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
//var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';
var html = '<table>';
// Write the header of the days of the week
html += '<tr>';
for(var i=0; i < 7;i++) {
html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
}
html += '</tr>';
//this.f = 'X';
var p = dm = this.f == 'M' ? 1 : (firstDayOfCurrentMonth == 0 ? -5 : 2);
var cellvalue;
for (var d, i=0, z=0; z<6; z++) {
html += '<tr>';
for (var k= 0; k < 7; k++) {
d = i + dm - firstDayOfCurrentMonth;
// Dates from prev month
if (d < 1){
cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;
html += '<td id="prevmonthdates">' +
'<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' +
'</td>';
// Dates from next month
} else if ( d > lastDateOfCurrentMonth){
html += '<td id="nextmonthdates">' + (p++) + '</td>';
// Current month dates
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
p = 1;
}
if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
z = 10; // no more rows
}
i++;
}
html += '</tr>';
}
// Closes table
html += '</table>';
document.getElementById("monthandyear").innerHTML = monthandyearhtml;
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function() {
// Start calendar
var c = new Calendar({
ParentID:"divcalendartable",
DaysOfWeek:[
'MON',
'TUE',
'WED',
'THU',
'FRI',
'SAT',
'SUN'
],
Months:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ],
Format:'dd/mm/yyyy'
});
c.showCurrent();
// Bind next and previous button clicks
getId('btnPrev').onclick = function(){
c.previousMonth();
};
getId('btnPrevYr').onclick = function(){
c.previousYear();
};
getId('btnNext').onclick = function(){
c.nextMonth();
};
getId('btnNextYr').onclick = function(){
c.nextYear();
};
}
// Get element by id
function getId(id) {
return document.getElementById(id);
}
});
html, body { margin: 0; padding: 0; }
table {
border-collapse: collapse;
font-family: Georgia, Times, serif;
}
th {
border: 1px solid #A8A8A8;
vertical-align: top;
}
td {
height: 150px;
width: 150px;
padding: 10px;
border: 1px solid #A8A8A8;
vertical-align: top;
text-align:center;
}
.divcalendar {
padding: 15px;
float:left;
/*background-color: #FFCC00;*/
}
/* Wrapper div. That makes the inner div into an inline element that can be centered with text-align.*/
#calendaroverallcontrols {
text-align: center;
}
/* This is a fluid div as width will be changing */
#calendarmonthcontrols {
display: inline-block;
/*background-color: #FF0000;*/
}
#calendarmonthcontrols > div, #calendarmonthcontrols > a {
display: inline-block;
}
#btnPrevYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnPrev {
text-decoration: none;
font-size: 35px;
margin-left: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
/*.yearspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}
.monthspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}*/
#monthandyearspan {
width: 50px;
font-size: 25px;
font-weight: bold;
margin-left: 20px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#monthandyear {
vertical-align: middle;
}
#btnNext {
text-decoration: none;
font-size: 35px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnNextYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#divcalendartable {
clear: both;
}
.daysheader {
background: #C0C0C0;
height: auto;
text-align: center;
}
#prevmonthdates {
background-color: #E0E0E0;
}
#nextmonthdates {
background-color: #E0E0E0;
}
#currentmonthdates {
background-color: #FFFFFF;
}
#cellvaluespan {
background: #FF0000;
}
#cellvaluelist {
background: #FFCC00;
}
.swim {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #445511;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.chrono {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #778899;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<div class="divcalendar">
<div id="calendaroverallcontrols">
<div id="calendarmonthcontrols">
<a id="btnPrevYr" href="#" title="Previous Year"><span></span></a>
<a id="btnPrev" href="#" title="Previous Month"><span><</span></a>
<div id="monthandyear"></div>
<a id="btnNext" href="#" title="Next Month"><span>></span></a>
<a id="btnNextYr" href="#" title="Next Year"><span></span></a>
</div>
</div>
<!-- extra -->
<div id="divcalendartable"></div>
</div>
Introduction: you don't need at all jQuery. Avoid to insert into jQuery Dom ready event the window.onload. It's useless.
The fast way to achieve your goal is:
Define a new css class:
.currentDay {
background-color: green !important;
}
In the method "Calendar.prototype.Calendar = function (y, m, n) {" change these lines:
// Current month dates
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
p = 1;
}
with:
} else {
var lDate = new Date();
if (d == lDate.getDate() && this.CurrentMonth == lDate.getMonth() &&
this.CurrentYear == lDate.getFullYear()) {
html += '<td id="currentmonthdates" class="currentDay">' + (d) + '</td>';
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
}
p = 1;
}
The previous change adds the class currentDay to today.
var Calendar = function (calen) {
//Store div id
this.divId = calen.ParentID;
// Days of week, starting on Sunday
this.DaysOfWeek = calen.DaysOfWeek;
// Months, stating on January
this.Months = calen.Months;
// Set the current month, year
var d = new Date();
this.CurrentMonth = d.getMonth();
this.CurrentYear = d.getFullYear();
var f = calen.Format;
//this.f = typeof(f) == 'string' ? f.charAt(0).toUpperCase() : 'M';
if (typeof(f) == 'string') {
this.f = f.charAt(0).toUpperCase();
} else {
this.f = 'M';
}
};
// Goes to next month
Calendar.prototype.nextMonth = function () {
if (this.CurrentMonth == 11) {
this.CurrentMonth = 0;
this.CurrentYear++;
} else {
console.log("this.CurrentMonth == ", this.CurrentMonth);
this.CurrentMonth++;
}
this.showCurrent();
};
// Goes to previous month
Calendar.prototype.previousMonth = function () {
if (this.CurrentMonth == 0) {
this.CurrentMonth = 11;
this.CurrentYear--;
} else {
this.CurrentMonth--;
}
this.showCurrent();
};
Calendar.prototype.previousYear = function () {
this.CurrentYear--;
this.showCurrent();
}
Calendar.prototype.nextYear = function () {
this.CurrentYear++;
this.showCurrent();
}
// Show current month
Calendar.prototype.showCurrent = function () {
this.Calendar(this.CurrentYear, this.CurrentMonth);
};
// Show month (year, month)
Calendar.prototype.Calendar = function (y, m, n) {
typeof(y) == 'number' ? this.CurrentYear = y : null;
typeof(y) == 'number' ? this.CurrentMonth = m : null;
typeof(y) == 'number' ? this.CurrDate = n : null;
// 1st day of the selected month
var firstDayOfCurrentMonth = new Date(y, m, 1).getDay();
// Last date of the selected month
var lastDateOfCurrentMonth = new Date(y, m + 1, 0).getDate();
// Last day of the previous month
var lastDateOfLastMonth = m == 0 ? new Date(y - 1, 11, 0).getDate() : new Date(y, m, 0).getDate();
// Write selected month and year. This HTML goes into <div id="year"></div>
//var yearhtml = '<span class="yearspan">' + y + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
//var monthhtml = '<span class="monthspan">' + this.Months[m] + '</span>';
// Write selected month and year. This HTML goes into <div id="month"></div>
var monthandyearhtml = '<span id="monthandyearspan">' + this.Months[m] + ' - ' + y + '</span>';
var html = '<table>';
// Write the header of the days of the week
html += '<tr>';
for (var i = 0; i < 7; i++) {
html += '<th class="daysheader">' + this.DaysOfWeek[i] + '</th>';
}
html += '</tr>';
//this.f = 'X';
var p = dm = this.f == 'M' ? 1 : (firstDayOfCurrentMonth == 0 ? -5 : 2);
var cellvalue;
for (var d, i = 0, z = 0; z < 6; z++) {
html += '<tr>';
for (var k = 0; k < 7; k++) {
d = i + dm - firstDayOfCurrentMonth;
// Dates from prev month
if (d < 1) {
cellvalue = lastDateOfLastMonth - firstDayOfCurrentMonth + p++;
html += '<td id="prevmonthdates">' +
'<span id="cellvaluespan">' + (cellvalue) + '</span><br/>' +
'</td>';
// Dates from next month
} else if (d > lastDateOfCurrentMonth) {
html += '<td id="nextmonthdates">' + (p++) + '</td>';
// Current month dates
} else {
var lDate = new Date();
if (d == lDate.getDate() && this.CurrentMonth == lDate.getMonth() && this.CurrentYear == lDate.getFullYear()) {
html += '<td id="currentmonthdates" class="currentDay">' + (d) + '</td>';
} else {
html += '<td id="currentmonthdates">' + (d) + '</td>';
}
p = 1;
}
if (i % 7 == 6 && d >= lastDateOfCurrentMonth) {
z = 10; // no more rows
}
i++;
}
html += '</tr>';
}
// Closes table
html += '</table>';
document.getElementById("monthandyear").innerHTML = monthandyearhtml;
document.getElementById(this.divId).innerHTML = html;
};
// On Load of the window
window.onload = function () {
// Start calendar
var c = new Calendar({
ParentID: "divcalendartable",
DaysOfWeek: [
'MON',
'TUE',
'WED',
'THU',
'FRI',
'SAT',
'SUN'
],
Months: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
Format: 'dd/mm/yyyy'
});
c.showCurrent();
// Bind next and previous button clicks
getId('btnPrev').onclick = function () {
c.previousMonth();
};
getId('btnPrevYr').onclick = function () {
c.previousYear();
};
getId('btnNext').onclick = function () {
c.nextMonth();
};
getId('btnNextYr').onclick = function () {
c.nextYear();
};
// Get element by id
function getId(id) {
return document.getElementById(id);
}
}
html, body {
margin: 0;
padding: 0;
}
table {
border-collapse: collapse;
font-family: Georgia, Times, serif;
}
th {
border: 1px solid #A8A8A8;
vertical-align: top;
}
td {
height: 150px;
width: 150px;
padding: 10px;
border: 1px solid #A8A8A8;
vertical-align: top;
text-align: center;
}
.divcalendar {
padding: 15px;
float: left;
/*background-color: #FFCC00;*/
}
/* Wrapper div. That makes the inner div into an inline element that can be centered with text-align.*/
#calendaroverallcontrols {
text-align: center;
}
/* This is a fluid div as width will be changing */
#calendarmonthcontrols {
display: inline-block;
/*background-color: #FF0000;*/
}
#calendarmonthcontrols > div, #calendarmonthcontrols > a {
display: inline-block;
}
#btnPrevYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnPrev {
text-decoration: none;
font-size: 35px;
margin-left: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
/*.yearspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}
.monthspan {
font-size: 20px;
font-weight: bold;
float: left;
margin-left: 5px;
margin-right: 5px;
}*/
#monthandyearspan {
width: 50px;
font-size: 25px;
font-weight: bold;
margin-left: 20px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#monthandyear {
vertical-align: middle;
}
#btnNext {
text-decoration: none;
font-size: 35px;
margin-right: 20px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#btnNextYr {
text-decoration: none;
font-size: 35px;
vertical-align: middle;
/*background: #00FFCC;*/
}
#divcalendartable {
clear: both;
}
.daysheader {
background: #C0C0C0;
height: auto;
text-align: center;
}
#prevmonthdates {
background-color: #E0E0E0;
}
#nextmonthdates {
background-color: #E0E0E0;
}
#currentmonthdates {
background-color: #FFFFFF;
}
#cellvaluespan {
background: #FF0000;
}
#cellvaluelist {
background: #FFCC00;
}
.swim {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #445511;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.chrono {
font-family: Arial, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background: #778899;
color: #F5F5F5;
margin-bottom: 5px;
padding: 5px;
}
.currentDay {
background-color: green !important;
}
<div class="divcalendar">
<div id="calendaroverallcontrols">
<div id="calendarmonthcontrols">
<a id="btnPrevYr" href="#" title="Previous Year"><span></span></a>
<a id="btnPrev" href="#" title="Previous Month"><span><</span></a>
<div id="monthandyear"></div>
<a id="btnNext" href="#" title="Next Month"><span>></span></a>
<a id="btnNextYr" href="#" title="Next Year"><span></span></a>
</div>
</div>
<!-- extra -->
<div id="divcalendartable"></div>
</div>
I guess you need to include jQuery.js.
https://learn.jquery.com/using-jquery-core/document-ready/

Categories

Resources