Scrollable Javascript Calendar - javascript

I am trying to make a calendar which can scroll between months using javascript. The calendar, at the moment, displays todays date and builds the months around it. I have a next button, which changes the month title, but the days remain completely unchanged. I have tried inserting "+ dayPerMonth[month+1] +" into the calendar body when 'next' is called, to no avail. It merely states above the table how many days the next month has.
var htmlContent ="";
var FebNumberOfDays ="";
var counter = 1;
var dateNow = new Date();
var month = dateNow.getMonth();
var nextMonth = month+1; //+1; //Used to match up the current month with the correct start date.
var prevMonth = month -1;
var day = dateNow.getDate();
var year = dateNow.getFullYear();
//Determing if February (28,or 29)
if (month == 1){
if ( (year%100!=0) && (year%4==0) || (year%400==0)){
FebNumberOfDays = 29;
}else{
FebNumberOfDays = 28;
}
}
// names of months and week days.
var monthNames = ["January","February","March","April","May","June","July","August","September","October","November", "December"];
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thrusday","Friday", "Saturday"];
var dayPerMonth = ["31", ""+FebNumberOfDays+"","31","30","31","30","31","31","30","31","30","31"];
// days in previous month and next one , and day of week.
var nextDate = new Date(nextMonth +' 1 ,'+year);
var weekdays= nextDate.getDay();
var weekdays2 = weekdays
var numOfDays = dayPerMonth[month];
// this leave a white space for days of pervious month.
while (weekdays>0){
htmlContent += "<td class='monthPre'></td>";
// used in next loop.
weekdays--;
}
// loop to build the calander body.
while (counter <= numOfDays){
// When to start new line.
if (weekdays2 > 6){
weekdays2 = 0;
htmlContent += "</tr><tr>";
}
// if counter is current day.
// highlight current day using the CSS defined in header.
if (counter == day){
htmlContent +="<td class='dayNow' onMouseOver='this.style.background=\"#FF0000\"; this.style.color=\"#FFFFFF\"' "+
"onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#FF0000\"'>"+counter+"</td>";
}else{
htmlContent +="<td class='monthNow' onMouseOver='this.style.background=\"#FF0000\"'"+
" onMouseOut='this.style.background=\"#FFFFFF\"'>"+counter+"</td>";
}
weekdays2++;
counter++;
}
function displayCalendar(){
var htmlContent ="";
var FebNumberOfDays ="";
var counter = 1;
var dateNow = new Date();
var month = dateNow.getMonth();
var nextMonth = month+1; //+1; //Used to match up the current month with the correct start date.
var prevMonth = month -1;
var day = dateNow.getDate();
var year = dateNow.getFullYear();
//Determing if February (28,or 29)
if (month == 1){
if ( (year%100!=0) && (year%4==0) || (year%400==0)){
FebNumberOfDays = 29;
}else{
FebNumberOfDays = 28;
}
}
// names of months and week days.
var monthNames = ["January","February","March","April","May","June","July","August","September","October","November", "December"];
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thrusday","Friday", "Saturday"];
var dayPerMonth = ["31", ""+FebNumberOfDays+"","31","30","31","30","31","31","30","31","30","31"];
// days in previous month and next one , and day of week.
var nextDate = new Date(nextMonth +' 1 ,'+year);
var weekdays = nextDate.getDay();
var weekdays2 = weekdays
var numOfDays = dayPerMonth[month];
// this leave a white space for days of pervious month.
while (weekdays>0){
htmlContent += "<td class='monthPre'></td>";
// used in next loop.
weekdays--;
}
// loop to build the calander body.
while (counter <= numOfDays){
// When to start new line.
if (weekdays2 > 6){
weekdays2 = 0;
htmlContent += "</tr><tr>";
}
// if counter is current day.
// highlight current day using the CSS defined in header.
if (counter == day){
htmlContent +="<td class='dayNow' onMouseOver='this.style.background=\"#FF0000\"; this.style.color=\"#FFFFFF\"' "+
"onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#FF0000\"'>"+counter+"</td>";
}else{
htmlContent +="<td class='monthNow' onMouseOver='this.style.background=\"#FF0000\"'"+
" onMouseOut='this.style.background=\"#FFFFFF\"'>"+counter+"</td>";
}
weekdays2++;
counter++;
}
// building the calendar html body.
var calendarBody = "<table class='calendar'> <tr class='monthNow'><th colspan='7'>"
+monthNames[month]+" "+ year +"</th></tr>";
calendarBody +="<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>"+
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarBody += "<tr>";
calendarBody += htmlContent;
calendarBody += "</tr></table>";
// set the content of div .
document.getElementById("calendar").innerHTML=calendarBody;
}
function next(){
var calendarBody2 = "<table class='calendar'> <tr class='monthNow'><th colspan='7'>"
+monthNames[month++]+" "+ year +"</th></tr>";
calendarBody2 +="<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>"+
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>"
;
calendarBody2 += "<tr>";
calendarBody2 += htmlContent ;
calendarBody2 += "</tr></table>";
// set the content of div .
document.getElementById("calendar").innerHTML=calendarBody2;
}
.btns{
width: 48%;
height: 5%;
}
#legend{
font-size: 20pt;
}
.ui-content{
margin-top: 1%;
}
.calendar{
width: 100%;
height: 80%;
}
.monthPre{
color: gray;
text-align: center;
}
.monthNow{
color: black;
text-align: center;
font-size: 20pt;
}
.dayNow{
border: 2px solid black;
color: #FF0000;
text-align: center;
font-size: 20pt;
}
.calendar td{
htmlContent: 2px;
width: 40px;
border: 2px solid black;
}
.monthNow th{
background-color: #000000;
color: #FFFFFF;
text-align: center;
}
.dayNames{
background: #FF0000;
color: #FFFFFF;
text-align: center;
}
<html>
<head>
<title>Calendar</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<button class='btns' onclick=prev()>Prev</button>
<button style=margin-left:3.25%; class='btns' onclick=next()>Next</button>
<body onload="displayCalendar()">
<div id="calendar"></div>
</body>
</html>

Try the below code, I have put the common code into getCal() method and updated little bit.
Similarly, added prev() method for previous
var htmlContent = "";
var FebNumberOfDays = "";
var counter = 1;
var dateNow = new Date();
var month = dateNow.getMonth();
var curMonth = month;
var day = dateNow.getDate();
var year = dateNow.getFullYear();
var curYear = year;
// names of months and week days.
var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"];
var dayPerMonth = ["31", "" + FebNumberOfDays + "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];
// days in previous month and next one , and day of week.
var nextDate, weekdays, weekdays2, numOfDays, nextMonth, prevMonth;
//to set the correct htmlContent
function getCal() {
htmlContent = "";
nextMonth = month + 1; //+1; //Used to match up the current month with the correct start date.
prevMonth = month - 1;
counter = 1;
//Determing if February (28,or 29)
if (month == 1) {
if ((year % 100 != 0) && (year % 4 == 0) || (year % 400 == 0)) {
FebNumberOfDays = 29;
} else {
FebNumberOfDays = 28;
}
}
// names of months and week days.
monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday"];
dayPerMonth = ["31", "" + FebNumberOfDays + "", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"];
// days in previous month and next one , and day of week.
nextDate = new Date(nextMonth + ' 1 ,' + year);
weekdays = nextDate.getDay();
weekdays2 = weekdays;
numOfDays = dayPerMonth[month];
// this leave a white space for days of pervious month.
while (weekdays > 0) {
htmlContent += "<td class='monthPre'></td>";
// used in next loop.
weekdays--;
}
// loop to build the calander body.
while (counter <= numOfDays) {
// When to start new line.
if (weekdays2 > 6) {
weekdays2 = 0;
htmlContent += "</tr><tr>";
}
// if counter is current day.
// highlight current day using the CSS defined in header.
if (counter == day && month == curMonth && year == curYear) {
htmlContent += "<td class='dayNow' onMouseOver='this.style.background=\"#FF0000\"; this.style.color=\"#FFFFFF\"' " +
"onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#FF0000\"'>" + counter + "</td>";
} else {
htmlContent += "<td class='monthNow' onMouseOver='this.style.background=\"#FF0000\"'" +
" onMouseOut='this.style.background=\"#FFFFFF\"'>" + counter + "</td>";
}
weekdays2++;
counter++;
}
}
function displayCalendar() {
getCal(); // to get the htmlContent
// building the calendar html body.
var calendarBody = "<table class='calendar'> <tr class='monthNow'><th colspan='7'>" +
monthNames[month] + " " + year + "</th></tr>";
calendarBody += "<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>" +
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarBody += "<tr>";
calendarBody += htmlContent;
calendarBody += "</tr></table>";
// set the content of div .
document.getElementById("calendar").innerHTML = calendarBody;
}
function next() {
debugger;
if(month+1==12){
++year;
month=-1;
}
var calendarBody = "<table class='calendar'> <tr class='monthNow'><th colspan='7'>" +
monthNames[++month] + " " + year + "</th></tr>";
calendarBody += "<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>" +
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarBody += "<tr>";
getCal(); // to get the htmlContent
calendarBody += htmlContent;
calendarBody += "</tr></table>";
// set the content of div .
document.getElementById("calendar").innerHTML = calendarBody;
}
function prev() {
if(month-1==-1){
--year;
month=12;
}
var calendarBody = "<table class='calendar'> <tr class='monthNow'><th colspan='7'>" +
monthNames[--month] + " " + year + "</th></tr>";
calendarBody += "<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>" +
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarBody += "<tr>";
getCal(); // to get the htmlContent
calendarBody += htmlContent;
calendarBody += "</tr></table>";
// set the content of div .
document.getElementById("calendar").innerHTML = calendarBody;
}
.btns {
width: 48%;
height: 5%;
}
#legend {
font-size: 20pt;
}
.ui-content {
margin-top: 1%;
}
.calendar {
width: 100%;
height: 80%;
}
.monthPre {
color: gray;
text-align: center;
}
.monthNow {
color: black;
text-align: center;
font-size: 20pt;
}
.dayNow {
border: 2px solid black;
color: #FF0000;
text-align: center;
font-size: 20pt;
}
.calendar td {
htmlContent: 2px;
width: 40px;
border: 2px solid black;
}
.monthNow th {
background-color: #000000;
color: #FFFFFF;
text-align: center;
}
.dayNames {
background: #FF0000;
color: #FFFFFF;
text-align: center;
}
<html>
<head>
<title>Calendar</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<button class='btns' onclick=prev()>Prev</button>
<button style=margin-left:3.25%; class='btns' onclick=next()>Next</button>
<body onload="displayCalendar()">
<div id="calendar"></div>
</body>
</html>

Related

Astra theme disabling javascript links

I have a working calendar demo. I have tested the code on more than one theme and everything works perfectly. The code however won't work with Astra Theme which is what I am using for my WordPress Website. I am not sure what the problem is at this point maybe someone would help me with this. This code also adds links to the dates. The problem is that Astra Theme strips the dates of the links when you change the date using the navigation buttons or date/month selector. Other themes seem to work perfectly. I checked console for errors and this is what I see:
(index):267 Uncaught TypeError: links is not a function
at previous ((index):267)
at HTMLButtonElement.onclick ((index):182)
The code is
<div class="wrapper">
<div class="container-calendar">
<h3 id="monthAndYear"></h3>
<div class="button-container-calendar">
<button id="previous" onclick="previous()">‹</button>
<button id="next" onclick="next()">›</button>
</div>
<table class="table-calendar" id="calendar" data-lang="en">
<thead id="thead-month"></thead>
<tbody id="calendar-body"></tbody>
</table>
<div class="footer-container-calendar">
<label for="month">Jump To: </label>
<select id="month" onchange="jump()">
<option value=0>Jan</option>
<option value=1>Feb</option>
<option value=2>Mar</option>
<option value=3>Apr</option>
<option value=4>May</option>
<option value=5>Jun</option>
<option value=6>Jul</option>
<option value=7>Aug</option>
<option value=8>Sep</option>
<option value=9>Oct</option>
<option value=10>Nov</option>
<option value=11>Dec</option>
</select>
<select id="year" onchange="jump()"></select>
</div>
</div>
</div>
<script>
function generate_year_range(start, end) {
var years = "";
for (var year = start; year <= end; year++) {
years += "<option value='" + year + "'>" + year + "</option>";
}
return years;
}
var today = new Date();
var currentMonth = today.getMonth();
var currentYear = today.getFullYear();
var selectYear = document.getElementById("year");
var selectMonth = document.getElementById("month");
var createYear = generate_year_range(2016, 2021);
/** or
* createYear = generate_year_range( 1970, currentYear );
*/
document.getElementById("year").innerHTML = createYear;
var calendar = document.getElementById("calendar");
var lang = calendar.getAttribute('data-lang');
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var dayHeader = "<tr>";
for (day in days) {
dayHeader += "<th data-days='" + days[day] + "'>" + days[day] + "</th>";
}
dayHeader += "</tr>";
document.getElementById("thead-month").innerHTML = dayHeader;
monthAndYear = document.getElementById("monthAndYear");
showCalendar(currentMonth, currentYear);
function next() {
currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
currentMonth = (currentMonth + 1) % 12;
showCalendar(currentMonth, currentYear);
links ()
}
function previous() {
currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
showCalendar(currentMonth, currentYear);
links ()
}
function jump() {
currentYear = parseInt(selectYear.value);
currentMonth = parseInt(selectMonth.value);
showCalendar(currentMonth, currentYear);
links ()
}
function showCalendar(month, year) {
var firstDay = (new Date(year, month)).getDay();
tbl = document.getElementById("calendar-body");
tbl.innerHTML = "";
monthAndYear.innerHTML = months[month] + " " + year;
selectYear.value = year;
selectMonth.value = month;
// creating all cells
var date = 1;
for (var i = 0; i < 6; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 7; j++) {
if (i === 0 && j < firstDay) {
cell = document.createElement("td");
cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
} else if (date > daysInMonth(month, year)) {
break;
} else {
cell = document.createElement("td");
cell.setAttribute("data-date", date);
cell.setAttribute("data-month", month + 1);
cell.setAttribute("data-year", year);
cell.setAttribute("data-month_name", months[month]);
cell.className = "date-picker";
cell.innerHTML = "<span>" + date + "</span>";
if (date === today.getDate() && year === today.getFullYear() && month === today.getMonth()) {
cell.className = "date-picker selected";
}
row.appendChild(cell);
date++;
}
}
tbl.appendChild(row);
}
}
function daysInMonth(iMonth, iYear) {
return 32 - new Date(iYear, iMonth, 32).getDate();
}
function links () {
document.querySelectorAll('td.date-picker > span').forEach(element => {
var year = element.parentElement.getAttribute('data-year');
var month = element.parentElement.getAttribute('data-month');
var day = element.textContent;
if (month.length === 1) {
month = "0" + month;
}
if (day.length === 1) {
day = "0" + day;
}
element.innerHTML = '' + element.textContent + ' '
})
}
links ()
</script>

Custom CSS in script

I am trying to modify the CSS of this code so that the articles are in columns of 3 articles side by side.
The CSS / script shows the articles one below the other, I would like to show them side by side.
Example:
1 - 2 - 3
4 - 5 - 6
Even though I have already made some modifications, the result I want is not showing up.
Does anyone know where the error code is?
<style>
/**
* Blogger Archive with Pagination - Default Theme
* Visit: http://www.dte.web.id
*/
#toc-outer {
font:normal 11px/14px Arial,Sans-Serif;
color:#666;
text-align:left;
margin:0px auto;
padding:15px;
background-color:white;
-webkit-box-shadow:0px 1px 4px rgba(0,0,0,0.6);
-moz-box-shadow:0px 1px 4px rgba(0,0,0,0.6);
box-shadow:0px 1px 4px rgba(0,0,0,0.6);
}
#loadingscript {
background:#F6EFBB url('data:image/gif;base64,R0lGODlhEAAQAPUAAP///wAAAO7u7lRUVAAAALa2tvb29tbW1uLi4mZmZggICL6+vk5OTtzc3BwcHCgoKOjo6GxsbCIiIkZGRpiYmH5+fsrKyoyMjKqqqvz8/NDQ0IaGhmBgYBYWFnJycsTExFpaWpKSkqSkpEBAQC4uLjQ0NJ6ennh4eA4ODjo6OrCwsAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAGo0CA0IDJAAhIR0YgbDYmhAKggyQIDp/mwYGcADzIEGDT0QgRjyrgQHAYIMiRgAmhII0EDGBUFQ0SCAAGD0YNAiJIAwtHSBUQGQZNCEZNVQQSTZkWEQpIChEWQpQAApYEmRkLgQAZGRpQSAALA0kQTQlCBSQlBZahDEIECotvBgxIwL1ZVYBCBxIEGgadIAAcSB0NWhdjahoEI9qZttexABiRQkEAIfkECQoAAAAsAAAAABAAEAAABmBAgBAgGhGEhJFoyGQQnsjniCk0PY+Aq4eZQACs2OfWcCI+vVbkWEEoXtHCtfR6ZhrYV6p+z9fTCVtDYFdGYgAGQmiEIoZ3SIptACNyUWgMdnhRBF5UJ3lZTwl7bkhKTEEAIfkECQoAAAAsAAAAABAAEAAABp1AgBAAGRGOQoxhKNRoAI8jAaAhjA7DQwcEWBy5HOnSwDh+MuUPQEp4FqQowGFqOA6ez8XgeMogAAgoZwAbXEN+TA0GKg5SChEWTEMgbJUFkgAWCQpsHRhMAggZTEYboxdDBkYEAwsABU8QKQSjIwACbCIZGRVScgSoF0cjAgAZHUcTAB5HAgIOHU9CEBMEl8gECRkf0qkYo1IMEExBADsAAAAAAAAAAAA=') no-repeat 50% 46%;
padding:10px;
font:bold 20px Georgia,Serif;
color:black;
height:400px;
text-indent:-9999px;
-webkit-box-shadow:inset 0px 0px 0px 5px #EAE0AD;
-moz-box-shadow:inset 0px 0px 0px 5px #EAE0AD;
box-shadow:inset 0px 0px 0px 5px #EAE0AD;
}
.itemposts {
margin:0px auto 5px;
height:auto;
background-color:white;
overflow:hidden;
display:block;
}
.itemposts h6 {
margin:0px auto 2px;
font:bold 12px/14px Arial,Sans-Serif;
background-color:#9BB009;
background-image:-webkit-linear-gradient(#9BB009, #AABD30);
background-image:-moz-linear-gradient(#9BB009, #AABD30);
background-image:-ms-linear-gradient(#9BB009, #AABD30);
background-image:-o-linear-gradient(#9BB009, #AABD30);
background-image:linear-gradient(#9BB009, #AABD30);
padding:10px 15px;
text-transform:none;
color:white;
}
.itemposts h6 a {
color:white;
text-decoration:none;
text-shadow:0px 1px 0px rgba(0,0,0,0.3);
}
.itemposts img {
float:left;
height:72px;
width:72px;
margin:2px 10px 2px 0px;
-webkit-box-shadow:none;
-moz-box-shadow:none;
box-shadow:none;
background-color:#fafafa;
border:1px solid #dcdcdc;
padding:4px;
}
.itemposts .iteminside {
padding:10px;
background-color:#f2f2f2;
background-image:-webkit-linear-gradient(#f2f2f2, white);
background-image:-moz-linear-gradient(#f2f2f2, white);
background-image:-ms-linear-gradient(#f2f2f2, white);
background-image:-o-linear-gradient(#f2f2f2, white);
background-image:linear-gradient(#f2f2f2, white);
border-top:1px solid #e5e5e5;
-webkit-box-shadow:inset 0px 1px 0px white;
-moz-box-shadow:inset 0px 1px 0px white;
box-shadow:inset 0px 1px 0px white;
}
.itemposts .itemfoot {
clear:both;
border:1px solid #EAE7DB;
padding:5px 10px;
margin:10px 0px 0px;
background-color:#FAFAE7;
color:#4B86C1;
overflow:hidden;
}
.itemposts .itemfoot a.itemrmore {
font-weight:bold;
color:#895F30;
float:right;
text-decoration:none;
}
.itemposts .itemfoot a.itemrmore:hover {
color:#9BB009;
text-decoration:underline;
}
#itempager {
background-color:#F2F0F1;
padding:30px 0px;
border-top:1px solid #E5E5E5;
-webkit-box-shadow:inset 0px 1px 0px white;
-moz-box-shadow:inset 0px 1px 0px white;
box-shadow:inset 0px 1px 0px white;
}
#pagination, #totalposts {
color:#999;
font:bold 10px Verdana,Arial,Sans-Serif;
padding:0px;
margin-bottom:10px;
text-align:center;
}
#pagination span, #pagination a {
border:1px solid #e5e5e5;
color:white;
display:inline;
margin:0 1px;
padding:2px 5px;
text-indent:0px;
background-color:#8899D0;
text-decoration:none;
}
#pagination span.actual,
#pagination a:hover {
background-color:#7483BC;
}
#pagination span.hidden {
display:none;
}
</style>
Script
<script>
var showPostDate = true,
showComments = true,
idMode = true,
sortByLabel = false,
labelSorter = "Games",
loadingText = "Loading...",
totalPostLabel = "Jumlah posting:",
jumpPageLabel = "Halaman",
commentsLabel = "Komentar",
rmoreText = "Selengkapnya ►",
prevText = "Sebelumnya",
nextText = "Berikutnya",
siteUrl = "https://elfenliedbrazil.blogspot.com/",
postPerPage = 6,
numChars = 370,
imgBlank = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAA3NCSVQICAjb4U/gAAAADElEQVQImWOor68HAAL+AX7vOF2TAAAAAElFTkSuQmCC";
</script>
<script type='text/javascript'>
//<![CDATA[
// -----------------------------------------------------------------------------------------
//
// Original:
// Modified by Taufik Nurrohman
//
// -----------------------------------------------------------------------------------------
var minpage = 6; // Minimum number to display the page
var maxpage = 10; // The maximum number of pages to display
var firstpage = 0; // Detect the first time it is executed
var pagernum = 0; // Contain the page number where we
var postsnum = 0; // Start the first page
var actualpage = 1; // Starting value of the current page (it will change if you click the pagination).
// This is the container template that will be used to insert the posts template, pagination and the posts count
document.write('<div id="toc-outer"><div id="results"></div><div id="itempager" style="position:relative;"><div id="pagination"></div><div id="totalposts"></div><a title="Taufik Nurrohman" style="display:block!important;visibility:visible!important;opacity:1!important;position:absolute;bottom:10px;right:14px;font:normal bold 8px Arial,Sans-Serif!important;color:#666;text-shadow:0 1px 0 rgba(255,255,255,.1);text-decoration:none;" href="http://hompimpaalaihumgambreng.blogspot.com/2012/03/daftar-isi-blogger-dengan-navigasi.html" target="_blank">►TN</a></div></div>');
var _results = document.getElementById('results');
var _pagination = document.getElementById('pagination');
var _totalposts = document.getElementById('totalposts');
// Build the table of contents framework
function showPagePosts(json) {
var entry, posttitle, posturl, postimg, postsumm, replies, monthnames, timepub, output = "";
if (pagernum === 0) {
postsnum = parseInt(json.feed.openSearch$totalResults.$t);
pagernum = parseInt(postsnum / postPerPage) + 1;
}
for (var i = 0; i < postPerPage; i++) {
if ("entry" in json.feed) {
if (i == json.feed.entry.length) break;
entry = json.feed.entry[i];
posttitle = entry.title.$t; // Get the post title
// Get rel="alternate" for truly post url
for (var k = 0, elen = entry.link.length; k < elen; k++) {
if (entry.link[k].rel == "alternate") {
posturl = entry.link[k].href; // This is your real post URL!
break;
}
}
// Get the comments count
for (var l = 0, clen = entry.link.length; l < clen; l++) {
if (entry.link[l].rel == "replies" && entry.link[l].type == "text/html") {
var commentsnum = entry.link[l].title.split(" ")[0]; // This is your comments count
break;
}
}
// If the Blogger-feed is set to SHORT, then the content is in the summary-field
postsumm = ("summary" in entry) ? entry.summary.$t.replace(/<br ?\/?>/ig, " ").replace(/<.*?>/g, "").replace(/[<>]/g, "") : ""; // Get the post summary
// Reduce post summaries to "numChars" characters.
// "numChars" is a variable. You determine the value
if (postsumm.length > numChars) {
postsumm = (numChars > 0 && numChars !== false) ? postsumm.substring(0, numChars) + '...' : "";
}
// Get the post date (e.g: 2012-02-07T12:56:00.000+07:00)
var _postdate = entry.published.$t,
_cdyear = _postdate.substring(0, 4), // Take 4 characters from the "postdate" beginning, it means the year (2012)
_cdmonth = _postdate.substring(5, 7), // Take 2 character 5 step from "postdate" beginning, it mean the month (02)
_cdday = _postdate.substring(8, 10); // Take 2 character 8 step from "postdate" beginning. it means the day (07)
// Month array template
monthnames = (idMode) ? ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Agt", "Sep", "Okt", "Nov", "Des"] : ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// The final product of the post date = (07 Feb 2012) (cdday monthnames cdyear)
timepub = (showPostDate) ? _cdday + ' ' + monthnames[parseInt(_cdmonth, 10) - 1] + ' ' + _cdyear + ' - ' : '';
// The final product of the comments count & comments label (10 Komentar) (commentsnum commentsLabel)
replies = (showComments) ? commentsnum + ' ' + commentsLabel : '';
// Get the post thumbnails
postimg = ("media$thumbnail" in entry) ? entry.media$thumbnail.url : imgBlank;
// Build the post template
output += '<div class="itemposts">';
output += '<h6>' + posttitle + '</h6>';
output += '<div class="iteminside"><img src="' + postimg + '" />';
output += '<span class="summary">' + postsumm + '</span></div>';
output += '<div style="clear:both;"></div><div class="itemfoot">' + timepub + replies + '<a class="itemrmore" href="' + posturl + '">' + rmoreText + '</a></div>';
output += '</div>';
}
}
// Put the whole template above into <div id="results"></div>
_results.innerHTML = output;
_create_pagination();
}
// Build the pagination
function _create_pagination() {
output = "";
var starter = 0;
output += ((actualpage > 1) ? '<a title="' + prevText + '" class="prevjson" href="javascript:_init_script(' + (actualpage - 1) + ')">' + prevText + '</a>' : '<span class="prevjson hidden">' + prevText + '</span>') + '<em style="font:inherit;color:inherit;" class="pagernumber">';
if (pagernum < (maxpage + 1)) {
for (starter = 1; starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
} else if (pagernum > (maxpage - 1)) {
if (actualpage < minpage) {
for (starter = 1; starter < (maxpage - 2); starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else if (pagernum - (minpage - 1) > actualpage && actualpage > (minpage - 1)) {
output += '1';
output += '2';
output += ' ... ';
for (starter = actualpage - 2; starter <= actualpage + 2; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
output += ' ... ';
output += '' + parseInt(pagernum - 1) + '';
output += '' + pagernum + '';
} else {
output += '1';
output += '2';
output += ' ... ';
for (starter = pagernum - (minpage + 1); starter <= pagernum; starter++) {
output += (starter == actualpage) ? '<span class="actual">' + starter + '</span>' : '' + starter + '';
}
}
}
output += '</em>' + ((actualpage < starter - 1) ? '<a title="' + nextText + '" class="nextjson" href="javascript:_init_script(' + (actualpage + 1) + ')">' + nextText + '</a>' : '<span class="nextjson hidden">' + nextText + '</span>');
_pagination.innerHTML = output;
_totalposts.innerHTML = totalPostLabel + ' ' + postsnum + ' - ' + jumpPageLabel + ' ' + ((actualpage * postPerPage) - (postPerPage - 1)) + ((actualpage < starter - 1) ? ' - ' + (actualpage * postPerPage) : "");
}
// Functions to remove and append the callback script that has been manipulated in the `start-index` parameter
function _init_script(n) {
var parameter = (n * postPerPage) - (postPerPage - 1), old, s,
head = document.getElementsByTagName('head')[0],
url = (sortByLabel) ? siteUrl + '/feeds/posts/summary/-/' + labelSorter + '?start-index=' + parameter : siteUrl + '/feeds/posts/summary?start-index=' + parameter; // Optional: Sort posts by a specific label
if (firstpage == 1) {
// Jump to top
document.documentElement.scrollTop = _results.offsetTop - 30;
document.body.scrollTop = _results.offsetTop - 30;
// Remove the old callback script
old = document.getElementById("TEMPORAL");
old.parentNode.removeChild(old);
}
_results.innerHTML = '<div id="loadingscript">' + loadingText + '</div>';
_pagination.innerHTML = '';
_totalposts.innerHTML = '';
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&max-results=' + postPerPage + '&orderby=published&alt=json-in-script&callback=showPagePosts';
s.id = 'TEMPORAL';
head.appendChild(s);
firstpage = 1;
actualpage = n;
}
// Execute the _init_script() function with parameter as `1` on page load
// So it will show the first page.
window.onload = function() {
_init_script(1);
};
//]]>
</script>
you can do with css. please apply the css code before closeing style tag
/* here the updated css */
#results {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.itemposts {
width: 33%;
margin-bottom: 10px;
}
/* media query for mobile responsiveness */
#media (max-width:882px) {
.itemposts {
width: calc(50% - 10px);
}
}
#media (max-width:576px) {
.itemposts {
width: 100%;
}
}

Rather than document.write, outputting in id/class of div

I’m trying to change the document.write to outputting in idor class so I can add it to a div
I tried to use document.getElementById("demo").innerHTML but it doesn't seem to work, not sure if I’m doing it correctly.
<html>
<body>
<p id="demo"></p>
<script type="text/javascript">
var d=new Date()
var daynumber=new Array("0","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th","13th","14th","15th","16th","17th","18th","19th","20th","21st","22nd","23rd","24th","25th","26th","27th","28th","29th","30th","31st","32nd")
var weekday=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var monthname=new Array("January","Febuary","March","April","May","June","July","August","September","October","November","December")
document.write(weekday[d.getDay()] + " ")
document.write(daynumber[d.getDate()] + " ")
// document.write(d.getDate() + " ")
document.write(monthname[d.getMonth()] + " ")
document.write(d.getFullYear())
</script>
</body>
</html>
Check Output or Edit Code on jsfiddle
It might help you
document.getElementById("demo").innerHTML = weekday[d.getDay()] + " "+daynumber[d.getDate()] + " "+monthname[d.getMonth()] + " "+d.getFullYear();
You could assign a new fuction with a closure over the target element.
But, as Chris Barr pointed out, "Overwriting built-in JavaScript functions is a bad idea."
document.write = (element => string => element.innerHTML += string)(document.getElementById('out'));
document.write('foo<br>');
document.write('bar');
<div id="out"></div>
You can use document.getElementById('idname') or even document.querySelector('#idname')
Here's a small demo with your code
//Vars
var d = new Date();
var outputElement = document.getElementById("current-date");
//Date Text arrays
var daynumber = ["1st", "2nd", "3rd", "4th", "5th", "6th", "7th", "8th", "9th", "10th", "11th", "12th", "13th", "14th", "15th", "16th", "17th", "18th", "19th", "20th", "21st", "22nd", "23rd", "24th", "25th", "26th", "27th", "28th", "29th", "30th", "31st", "32nd"];
var weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var monthname = ["January", "Febuary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
//Build up a string
var dateStr = weekday[d.getDay()] +
", the " + daynumber[d.getDate() - 1] +
" of " + monthname[d.getMonth()] +
", " + d.getFullYear();
//Output to screen
outputElement.innerHTML = dateStr
#current-date {
padding: 1px 4px;
background: #EFEFEF;
border: 1px solid #CCC;
border-radius: 4px;
}
<p>
Today's date is <strong id="current-date"></strong>
</p>

Issues with php/javascript regarding value

So I have this function that creates textareas depending on the month. So if it is March, then 31 textareas, April, then 30 textareas and so on. When the user clicks on one textarea and then the submit button, the value of the textarea should be submitted to the db. So if the user marks 2018-02-04, then that date should be inserted into the db. But, my problem right now is that the only value that is submitted is the last date of each month. Not sure why, and dont know how to solve it. Think it might be something with IDs. Or that I need to send the value in as an array. But not sure on how to do it.
Functions:
var showDate = new Date();
var months = ["Januari", "Februari", "March", "April", "May", "June",
"July", "Augusti", "September", "October", "November", "December"];
var weeks = ["Sunday","Monday","Tuseday","Wednesday","Thursday","Friday","Saturday"];
function drawTable(forDate) {
var daysInMonth = new Date(forDate.getFullYear(),forDate.getMonth()+1,0).getDate();
var cellsToDraw = daysInMonth;
var newdate = forDate.getFullYear() +"-"+ ("0"+ (forDate.getMonth() + 1)).slice(-2);
var table = document.getElementById("table");
table.innerHTML = "";
for (var r = 0; r < (daysInMonth / 7); r++) {
var newRow = document.createElement("tr");
table.appendChild(newRow);
for (var c = 0; c < 31 && cellsToDraw > 0; c++) {
var day1 = ("0" + (c + 1)).slice(-2);
var textarea = document.createElement("textarea");
textarea.setAttribute("placeholder", day1 );
//textarea.setAttribute("id", some_value); does not work
newRow.appendChild(textarea);
textarea.setAttribute("name", "day");
textarea.setAttribute("day", newdate + "-" + day1 )
textarea.innerHTML = newdate + "-" + day1;
cellsToDraw--;
}
}
}
window.onload = function() {
document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
drawTable(showDate );
};
function next() {
if (showDate.getMonth() == 11) {
showDate.setMonth( 0 );
showDate.setFullYear( showDate.getFullYear()+1 );
} else {
showDate.setMonth( showDate.getMonth()+1 );
}
document.getElementById("displayingMonth").innerHTML = months[showDate.getMonth()];
drawTable( showDate );
}
html:
<form class="" action="index.php" method="post">
<table id="table" cellspacing="0" cellpadding="0" border-collapse="collapse";>
<br>
<input id="btn" type="submit" name="" value="Send">
</form>
php:
<?php
include ("connection.php");
$day = mysqli_real_escape_string($conn, $_REQUEST['day']);
$stmt = "INSERT INTO table (day) VALUES('$day')";
if(empty($day)){
$_SESSION['error'] = "Please fill in required fields";
header('Location: index.php', true, 303);
exit();
} else {
if (mysqli_query($conn, $stmt)) {
header('Location: index.php', true, 303);
exit;
}else {
$error= "Error: " .mysqli_error($conn);
echo "$error";
}
}
?>
My test php:
$days = $_request['day'];
$error = array();
foreach ($days as $day) {
$day = mysqli_real_escape_string($conn, $day);
if (empty($day)) {
$error[] = array(
'day' => $day,
'error' => 'day was empty'
);
}
else if (
!mysqli_query(
$conn,
"INSERT INTO table (day) VALUES('$day)')"
)
) {
$error[] = array(
'day' => $day,
'error' => mysqli_error($conn)
);
}
}
if (count($error)) {
print_r($error);
}
header('Location: index.php', true, 303);
All help is appriciated! :)
As I understood, you want to send date selected by user to server but last date of month is getting submitted right now. If this is your purpose and issue respectively then see it
ON JSFIDDLE.NET
https://jsfiddle.net/wyn1cd5b/1/
STACKOVERFLOW SNIPPET
function drawTable(forDate) {
var table = document.getElementById('table')
var year = forDate.getFullYear()
var month = forDate.getMonth() + 1
document.getElementById('date').innerHTML = months[month - 1]
table.innerHTML = ''
var daysInMonth = new Date(year, month, 0).getDate()
for (i = 1; i <= daysInMonth; i++) {
table.insertAdjacentHTML('beforeend', '<textarea class="date-item" onclick="selectThis(this)">' + year + '-' + (month < 10 ? '0' + month : month) + '-' + (i < 10 ? '0' + i : i) + '</textarea>')
}
}
function selectThis(textarea) {
if (typeof selectedDate !== 'undefined')
selectedDate.classList.remove('selected-date')
selectedDate = textarea
selectedDate.classList.add('selected-date')
}
function send() {
if (typeof selectedDate === 'undefined')
alert('No date selected')
else
// I have printed selected here. do whatever you want with it
document.getElementById('info').innerHTML = 'Will send <b>' + selectedDate.value + '</b> to server'
return false
}
function next() {
if (showDate.getMonth() === 11) {
showDate.setMonth(0)
showDate.setFullYear(showDate.getFullYear() + 1)
} else {
showDate.setMonth(showDate.getMonth() + 1)
}
drawTable(showDate)
return false
}
window.onload = function() {
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
// days = ['Sunday', 'Monday', 'Tuseday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
showDate = new Date()
drawTable(showDate)
}
.date-item {
cursor: pointer;
}
.selected-date {
background: #dbdbdb;
}
<form class="" action="index.php" method="post">
<table id="table" cellspacing="0" cellpadding="0" border-collapse="collapse" ;>
<h1 id="date"></h1>
</table>
<p id="info">Select date by clicking on it</p>
<input id="btn" type="submit" name="" onclick="return send()" value="Send">
<input id="btn" type="submit" name="" onclick="return next()" value="Next">
</form>

Creating a Table with the days of the Month

I've several problems at the moment and I can't see to find the solution.
I insert two dates and I have the list of month, year between them.
I'm trying to make a table to with:
Number of Day
Name of Day
and be able to:
select month/year from a combobox (this gives the amount of days in the month)
if it's exists you can use pagination to go to the next month,etc...
MY LAYOUT
First Problem:
I'm using Java to pass a List to JavaScript and I get this in the combobox:
The second problem is basically I cant do anything else without the combobox correct value.
<%
String initialDayEnd = session.getAttribute("initialSystemDate").toString();
String finalDayEnd = session.getAttribute("finalSystemDate").toString();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
Calendar beginCalendar = Calendar.getInstance();
Calendar finishCalendar = Calendar.getInstance();
try {
beginCalendar.setTime(format.parse(initialDayEnd));
finishCalendar.setTime(format.parse(finalDayEnd));
} catch (ParseException e) {
e.printStackTrace();
}
List<String> dateList = new ArrayList<String>();
List<String> dateListMonthYear = new ArrayList<String>();
String[] dateSplitted;
while (beginCalendar.before(finishCalendar)) {
// add one month to date per loop
String date = format.format(beginCalendar.getTime()).toUpperCase();
System.out.println(date);
beginCalendar.add(Calendar.MONTH, 1);
dateSplitted = date.split("/");
dateList.add(dateSplitted[0] + "/" + dateSplitted[1] + "/" + dateSplitted[2]);
dateListMonthYear.add(dateSplitted[1] + "/" + dateSplitted[2]);
}
%>
<input type="hidden" id="dates" value="<%=dateListMonthYear%>">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th class="text-center">#</th>
<th class="text-center">Day</th>
</tr>
</thead>
<tfoot>
<tr>
<th class="text-center">#</th>
<th class="text-center">Day</th>
</tr>
</tfoot>
<tbody class="dayTableBody">
<%--JSON ARRAY CREATES THE TABLE--%>
</tbody>
</table>
JS:
$(document).ready(function() {
var dates = $('#dates').val();
console.log(dates);
$('#dataTable').DataTable({
"lengthMenu" : dates
});
});
var day, month, year;
$('.dates').change(DatesChanged);
DatesChanged();
function DatesChanged() {
var date = $('.dates').val();
var splitDate = date.split("/");
day = splitDate[0];
month = splitDate[1];
year = splitDate[2];
var maxDays = daysInMonth(month, year);
CreateJSONArray(maxDays, date);
}
function daysInMonth(month, year) {
return new Date(year, month, 0).getDate();
}
function CreateJSONArray(maxDays, date) {
var arr = [];
var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var d;
for (var day = 1; day <= maxDays; day++) {
d = new Date(date);
arr.push({
"dayNumber": day,
"dayName": dayNames[d.getDay()],
"monthName": monthNames[month - 1],
"year": d.getYear() + 1900
});
date = d.setDate(d.getDate() + 1);
}
DisplayTable(arr);
console.log(arr);
}
function DisplayTable(data) {
//heading
document.getElementsByClassName("month-year")[0].innerHTML = data[0].monthName + ", " + data[0].year;
//Table
$('.dayTableBody').empty();
$.each(data, function (index, value) {
data += '<tr align="center">';
data += '<td>' + value.dayNumber + '<input type="hidden" name="dayNumber" value="' + value.dayNumber + '">' + '</td>';
data += '<td>' + value.dayName + '</td>';
//get amount of types of Clients
var clientTypes = ["Individual","Corporation"];
for (var i = 0; i < clientTypes.length; i++) {
data += '<td>' + '<input class="text-center amountOfClients" type="number" value="0" name="amountOfClients-' + clientTypes[i] + '" data-error="Please, insert a value" required>' + '</td>'
data += '<div class="help-block with-errors"></div>'
}
data += '</tr>';
});
$('.dayTableBody').append(data);
}
Maybe there is a simpler way to make this?

Categories

Resources