How to make ajax get the data without refresh on jQuery? - javascript

I want to be able to get the data using ajax without having to load the page to get the up to date data.
Here is the function I'm using to get the data from another page URL (I have to refresh to get the up to date data):
$.ajax({
url: "/data.aspx",
success: function(myObj) {
try {
var d = new Date();
var s = new String();
var Day = d.getDate();
var Month = d.getMonth() + 1;
var Year = d.getFullYear();
s = (Month + "/" + Day + "/" + Year).toString();
var Start = myObj.indexOf("var WPQ1ListData = {");
var End = myObj.indexOf("var WPQ1SchemaData");
var Str = myObj.substring(Start + 19, End - 1);
var Objects = Str.split(',');
var count = 0;
var AllEvents = "";
$("#calendarItems").empty();
for (var i = 0; i < Objects.length; i++) {
if ((Objects[i].indexOf('Title') > -1) || (Objects[i].indexOf('"EventDate"') > -1)) {
count++;
TwoDimObjects = Objects[i].split(":");
AllEvents += TwoDimObjects[1];
if (count % 2 == 0) {
AllEvents += "_-_";
}
}
}
var index1, index2, index3, Split, Decoded, FullDate, Month, YearwithTitle, Title, MonthNum, DayNum,
YearNum, dateParts, months, selectedMonthName, CalendarItem, EventCounter;
EventCounter = 0;
CalendarItem = "";
months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
DiffDate = AllEvents.split('"').join(' ');
DiffDate2 = DiffDate.split("_-_");
for (var j = 0; j < DiffDate2.length - 1; j++) {
Decoded = DiffDate2[j].split("\\u002f").join("\\");
Split = Decoded.substring(2, Decoded.length);
index1 = Split.indexOf(" ");
index2 = Split.indexOf(" ");
YearwithTitle = Split.substr(0, index1) + Split.substr(index2 + 1);
index3 = YearwithTitle.indexOf(" ");
FullDate = YearwithTitle.substring(0, index3);
Title = YearwithTitle.substring(index3 + 1, YearwithTitle.length);
FullDate, dateParts = FullDate.split(/\\|\//), MonthNum = dateParts[0], DayNum = dateParts[1], YearNum = dateParts[2];
ConvertDate = FullDate.split("\\").join("/");
var CurrentDate = new Date(s);
var CalendarItemDate = new Date(ConvertDate);
if (CurrentDate <= CalendarItemDate) {
EventCounter++;
if (EventCounter <= 4) {
selectedMonthName = months[MonthNum];
CalendarItem += '<li>' + selectedMonthName + " " + DayNum + " - " + Title + '</li>';
}
}
}
document.getElementById("calendarItems").innerHTML += CalendarItem;
} catch (err) {
alert(err)
}
}
}
);

Related

Javascript compatibility with desktop Safari [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I wrote the following code for displaying a different image depending on the date (right now this example just console logs a message). The code works fine in Chrome and Firefox on Mac, but does not work correctly or give any errors on Safari (in Safari the message does not change depending on the date, it just says the same). How is Safari processing this differently? How can I get this to work on Safari with minimal changes?
Here's a working repl.
Here's the code:
/* change these dates */
var ddt = new Date("2019, 8, 22");
var pre = new Date("2019, 8, 23");
var ton = new Date("2019, 8, 26");
var post = new Date("2019, 8, 27");
// todays date
var currDate = new Date();
var mm = currDate.getMonth() + 1;
var dd = currDate.getDate();
var yyyy = currDate.getFullYear();
// Get the date parts
var ddtDay = ddt.getDate();
var ddtMonth = ddt.getMonth() + 1;
var ddtYear = ddt.getFullYear();
//console.log(ddtYear, ddtMonth, ddtDay);
var preDay = pre.getDate();
var preMonth = pre.getMonth() + 1;
var preYear = pre.getFullYear();
//console.log(preYear, preMonth, preDay);
var tonDay = ton.getDate();
var tonMonth = ton.getMonth() + 1;
var tonYear = ton.getFullYear();
//console.log(tonYear, tonMonth, tonDay);
var postDay = post.getDate();
var postMonth = post.getMonth() + 1;
var postYear = post.getFullYear();
//console.log(postYear, postMonth, postDay);
// format the date parts
if (ddtDay < 10) {
ddtDay = '0' + ddtDay;
}
if (ddtMonth < 10) {
ddtMonth = '0' + ddtMonth;
}
if (preDay < 10) {
preDay = '0' + preDay;
}
if (preMonth < 10) {
preMonth = '0' + preMonth;
}
if (tonDay < 10) {
tonDay = '0' + tonDay;
}
if (tonMonth < 10) {
tonMonth = '0' + tonMonth;
}
if (postDay < 10) {
postDay = '0' + postDay;
}
if (tonMonth < 10) {
postMonth = '0' + postMonth;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var ddtF = (ddtYear + '-' + ddtMonth + '-' + ddtDay);
var preF = (preYear + '-' + preMonth + '-' + preDay);
var tonF = (tonYear + '-' + tonMonth + '-' + tonDay);
var postF = (postYear + '-' + postMonth + '-' + postDay);
var today = (yyyy + '-' + mm + '-' + dd);
console.log(ddtF);
console.log(preF);
console.log(tonF);
console.log(postF);
console.log(today);
// logic
if (today >= postF) {
console.log('post');
} else if (today === tonF) {
console.log('ton');
} else if (today < tonF && today >= preF) {
console.log('pre');
} else if (today <= ddtF) {
console.log('ddt');
}
"2019, 8, 22" is not a portable date format. The Date constructor has a portable calling sequence where you give each component of the date as a separate argument, so use
var ddt = new Date(2019, 7, 22);
and similarly for all the other variables.
And remember that months are counted from 0 in JavaScript, so you need to subtract 1 from the month argument (August is 7).
/* change these dates */
var ddt = new Date(2019, 7, 22);
var pre = new Date(2019, 7, 23);
var ton = new Date(2019, 7, 26);
var post = new Date(2019, 7, 27);
// todays date
var currDate = new Date();
var mm = currDate.getMonth() + 1;
var dd = currDate.getDate();
var yyyy = currDate.getFullYear();
// Get the date parts
var ddtDay = ddt.getDate();
var ddtMonth = ddt.getMonth() + 1;
var ddtYear = ddt.getFullYear();
//console.log(ddtYear, ddtMonth, ddtDay);
var preDay = pre.getDate();
var preMonth = pre.getMonth() + 1;
var preYear = pre.getFullYear();
//console.log(preYear, preMonth, preDay);
var tonDay = ton.getDate();
var tonMonth = ton.getMonth() + 1;
var tonYear = ton.getFullYear();
//console.log(tonYear, tonMonth, tonDay);
var postDay = post.getDate();
var postMonth = post.getMonth() + 1;
var postYear = post.getFullYear();
//console.log(postYear, postMonth, postDay);
// format the date parts
if (ddtDay < 10) {
ddtDay = '0' + ddtDay;
}
if (ddtMonth < 10) {
ddtMonth = '0' + ddtMonth;
}
if (preDay < 10) {
preDay = '0' + preDay;
}
if (preMonth < 10) {
preMonth = '0' + preMonth;
}
if (tonDay < 10) {
tonDay = '0' + tonDay;
}
if (tonMonth < 10) {
tonMonth = '0' + tonMonth;
}
if (postDay < 10) {
postDay = '0' + postDay;
}
if (tonMonth < 10) {
postMonth = '0' + postMonth;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var ddtF = (ddtYear + '-' + ddtMonth + '-' + ddtDay);
var preF = (preYear + '-' + preMonth + '-' + preDay);
var tonF = (tonYear + '-' + tonMonth + '-' + tonDay);
var postF = (postYear + '-' + postMonth + '-' + postDay);
var today = (yyyy + '-' + mm + '-' + dd);
console.log(ddtF);
console.log(preF);
console.log(tonF);
console.log(postF);
console.log(today);
// logic
if (today >= postF) {
console.log('post');
} else if (today === tonF) {
console.log('ton');
} else if (today < tonF && today >= preF) {
console.log('pre');
} else if (today <= ddtF) {
console.log('ddt');
}

why nextButton() function is not running?

I'm still newbie and trying to make a simple website, one of my feature is calendar.
why is my function nextbutton() is not running?
I also need some critics where and what should i change in coding. thank you so much!
function calendar(){
date = new Date();
month = date.getMonth();
year = date.getFullYear();
var dayOfweek = date.getDay();
var day = date.getDate();
var nameOftheMonth = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
var nameOftheDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var nextMonth = month+1;
var prevMonth = month-1;
var numberOfDays = new Date(year, month, 1).getDay();
var TotalNumOfDays = new Date(year, month+1, 0).getDate();
var num2 = numberOfDays+1;
var num = 1;
var content = "";
content += "<button><----</button><div>" + nameOftheMonth[month] + " " + year + "</div><button>----></button>";
content += "<br/><table><tr>";
for (count=0;count <= nameOftheDays.length-1; count++){
content += "<td>" + nameOftheDays[count] + "</td>";
if(count === nameOftheDays.length-1){
content += "</tr><tr>";
}
}
while (numberOfDays > 0) {
content += "<td></td>";
numberOfDays--;
}
while (num <= TotalNumOfDays){
content += "<td>" + num + "</td>";
if (num2 > 6) {
num2 = 0;
content += "</tr><tr>"
}
num2++;
num++;
}
document.getElementById("calendar").innerHTML = content;
document.getElementsByTagName("button")[0].setAttribute("id", "prevbutton");
document.getElementsByTagName("button")[0].setAttribute("onclick", "prevButton()");
document.getElementsByTagName("button")[1].setAttribute("id", "nextButton");
document.getElementsByTagName("button")[1].setAttribute("onclick", "nextButton()");
document.getElementsByTagName("div")[1].setAttribute("id", "dateToday");
}
function nextButton(){
if(month != null){
month = month++;
}
}
<div id="calendar"></div>
<script language="JavaScript">
var month=-1;
function calendar(){
date = new Date();
if(month===-1){
month =date.getMonth();
}
year = date.getFullYear();
var dayOfweek = date.getDay();
var day = date.getDate();
var nameOftheMonth = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
var nameOftheDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var nextMonth = month+1;
var prevMonth = month-1;
var numberOfDays = new Date(year, month, 1).getDay();
var TotalNumOfDays = new Date(year, month+1, 0).getDate();
var num2 = numberOfDays+1;
var num = 1;
var content = "";
content += "<button><----</button><div>" + nameOftheMonth[month] + " " + year + "</div><button>----></button>";
content += "<br/><table><tr>";
for (count=0;count <= nameOftheDays.length-1; count++){
content += "<td>" + nameOftheDays[count] + "</td>";
if(count === nameOftheDays.length-1){
content += "</tr><tr>";
}
}
while (numberOfDays > 0) {
content += "<td></td>";
numberOfDays--;
}
while (num <= TotalNumOfDays){
content += "<td>" + num + "</td>";
if (num2 > 6) {
num2 = 0;
content += "</tr><tr>"
}
num2++;
num++;
}
document.getElementById("calendar").innerHTML = content;
document.getElementsByTagName("button")[0].setAttribute("id", "prevbutton");
document.getElementsByTagName("button")[0].setAttribute("onclick", "prevButton()");
document.getElementsByTagName("button")[1].setAttribute("id", "nextButton");
document.getElementsByTagName("button")[1].setAttribute("onclick", "nextButton()");
document.getElementsByTagName("div")[1].setAttribute("id", "dateToday");
}
function nextButton(){
if(month != null){
document.getElementById("calendar").innerHTML ="";
month++;
calendar()
}
}
</script>
Try this out. I pulled the vars out of the calendar() function, and set your nextButton() function (which works, by the way, just do a console.log to see) to call the calendar function every time. Also, to increment, just do var++
var date = new Date();
var month = date.getMonth();
var year = date.getFullYear();
function calendar(month) {
var dayOfweek = date.getDay();
var day = date.getDate();
var nameOftheMonth = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
var nameOftheDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
var nextMonth = month + 1;
var prevMonth = month - 1;
var numberOfDays = new Date(year, month, 1).getDay();
var TotalNumOfDays = new Date(year, month + 1, 0).getDate();
var num2 = numberOfDays + 1;
var num = 1;
var content = "";
content += "<button><----</button><div>" + nameOftheMonth[month] + " " + year + "</div><button>----></button>";
content += "<br/><table><tr>";
for (count = 0; count <= nameOftheDays.length - 1; count++) {
content += "<td>" + nameOftheDays[count] + "</td>";
if (count === nameOftheDays.length - 1) {
content += "</tr><tr>";
}
}
while (numberOfDays > 0) {
content += "<td></td>";
numberOfDays--;
}
while (num <= TotalNumOfDays) {
content += "<td>" + num + "</td>";
if (num2 > 6) {
num2 = 0;
content += "</tr><tr>"
}
num2++;
num++;
}
document.getElementById("calendar").innerHTML = content;
document.getElementsByTagName("button")[0].setAttribute("id", "prevbutton");
document.getElementsByTagName("button")[0].setAttribute("onclick", "prevButton()");
document.getElementsByTagName("button")[1].setAttribute("id", "nextButton");
document.getElementsByTagName("button")[1].setAttribute("onclick", "nextButton()");
document.getElementsByTagName("div")[1].setAttribute("id", "dateToday");
}
function nextButton() {
if (month != null) {
console.log(month);
month++;
calendar(month);
}
}
<body onload="calendar(month)">
<div id="calendar">
</div>
<div id="today">
</div>
</body>
nextButton click is not working because it is a dynamically created element.
So we need to attach the click listeners on newly created DOM elements using, addEventListener.
document.getElementsByTagName("button")[1].addEventListener('click', yourFunction);
I have used simple JS prototyping to modify the code slightly, this way you can add more methods to your calendar and have multiple instances of it.
function Calendar(month,date,year) {
this.month = month, this.date = date, this.year = year;
this.nameOftheMonth = ["JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"];
this.nameOftheDays = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
}
Calendar.prototype.init = function() {
this.date = new Date();
this.month = this.date.getMonth();
this.year = this.date.getFullYear();
this.render();
}
Calendar.prototype.render = function() {
var dayOfweek = this.date.getDay();
var day = this.date.getDate();
var nextMonth = this.month+1;
var prevMonth = this.month-1;
var numberOfDays = new Date(this.year, this.month, 1).getDay();
var TotalNumOfDays = new Date(this.year, this.month+1, 0).getDate();
var num2 = numberOfDays+1;
var num = 1;
var content = "";
content += "<button><----</button><div>" + this.nameOftheMonth[this.month] + " " + this.year + "</div><button>----></button>";
content += "<br/><table><tr>";
for (count=0;count <= this.nameOftheDays.length-1; count++){
content += "<td>" + this.nameOftheDays[count] + "</td>";
if(count === this.nameOftheDays.length-1){
content += "</tr><tr>";
}
}
while (numberOfDays > 0) {
content += "<td></td>";
numberOfDays--;
}
while (num <= TotalNumOfDays){
content += "<td>" + num + "</td>";
if (num2 > 6) {
num2 = 0;
content += "</tr><tr>"
}
num2++;
num++;
}
document.getElementById("calendar").innerHTML = content;
document.getElementsByTagName("button")[0].setAttribute("id", "prevbutton");
document.getElementsByTagName("button")[1].setAttribute("id", "nextButton");
document.getElementsByTagName("button")[0].addEventListener('click', (function() {
this.prevButton();
}).bind(this));
document.getElementsByTagName("button")[1].addEventListener('click', (function() {
this.nextButton();
}).bind(this));
document.getElementsByTagName("div")[1].setAttribute("id", "dateToday");
}
Calendar.prototype.nextButton = function(){
if(this.month !== null){
this.month += 1;
this.render();
}
}
Calendar.prototype.prevButton = function(){
if(this.month !== null){
this.month -= 1;
this.render();
}
}
var c =new Calendar();
c.init();
<div id="calendar">
</div>

Reorder the output of a javascript function

Here is my code. It currently creates this:
but I need it to display the days of the week below the dates. I know its probably just a matter of switching 2 lines around but my javascript skills are limited and i'm struggling. any help greatly appreciated.
var Timeline = function (container, date) {
this.daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
this.weekDays = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
this.monthsOfYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
this.dayNumbers = {
"sunday": 0,
"monday": 1,
"tuesday": 2,
"wednesday": 3,
"thursday": 4,
"friday": 5,
"saturday": 6
};
this.initialize = function () {
this.isIE6 = (jQuery.browser.msie && jQuery.browser.version == "6.0");
this.container = $("#" + container);
if (!this.container.length) {
alert("can not locate container element \"" + container + "\"!");
return;
}
this.bubble = new Timeline.Bubble(this);
this.date = (date) ? date : new Date();
this.readEvents();
this.placeHolders = this.setupPlaceHolders();
this.container.addClass("timeline");
this.render();
},
this.readEvents = function () {
this.events = [];
var eventList = this.container.find("ul");
var eventItems = eventList.find("li");
for (var i = 0; i < eventItems.length; i++) {
var date = new Date(eventItems[i].getAttribute("title"));
if (date == "Invalid Date") continue;
this.events[i] = {
name: eventItems[i].className,
date: date,
day: date.getDate(),
month: date.getMonth(),
year: date.getFullYear(),
content: jQuery(eventItems[i]).html()
};
}
var j, tmp, events = this.events;
for (var i = 1; i < events.length; i++) {
tmp = this.events[i];
for (j = i; j > 0 && events[j - 1].date > tmp.date; j--)
events[j] = events[j - 1];
events[j] = tmp;
}
eventList.remove();
}
this.render = function () {
this.placeHolders.arrows.empty();
this.placeHolders.top.empty();
this.placeHolders.bottom.empty();
var monthRepresentation = this.getMonthRepresentation();
for (var i = 0; i < monthRepresentation.length; i++)
this.renderDay(this.placeHolders.top, this.placeHolders.bottom, monthRepresentation[i]);
if (this.isIE6) this.handleIE6Issues();
this.setupArrows();
}
this.handleIE6Issues = function () {
var clone = this.placeHolders.top.clone(true);
this.container.append(clone);
clone.css({
left: "-1000px",
top: "-1000px"
});
var width = clone.outerWidth();
clone.remove();
this.placeHolders.top.css({
width: width + "px"
});
this.placeHolders.bottom.css({
width: width + "px"
});
}
this.renderDay = function (topRow, bottomRow, data) {
var cssClass = "";
cssClass += (this.isToday(data.number)) ? "today" : "";
cssClass += (data.events.length) ? " event" : "";
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
nameEl = topRow.find("div:last");
numbEl = bottomRow.find("div:last");
if (data.events.length == 0) return;
var self = this;
var enterClosure = function (e) {
self.onMouseEnter(e);
};
var leaveClosure = function (e) {
self.onMouseLeave(e);
};
nameEl.bind("mouseenter", data, enterClosure);
numbEl.bind("mouseenter", data, enterClosure);
nameEl.bind("mouseleave", data, leaveClosure);
numbEl.bind("mouseleave", data, leaveClosure);
}
this.setupArrows = function () {
var dateString = this.monthsOfYear[this.date.getMonth()] + " " + this.date.getFullYear();
var html = "";
html += "<div class=\"timeline_lastyear\" title=\"Previous Year\"></div>"
html += "<div class=\"timeline_lastmonth\" title=\"Previous Month\"></div>"
html += "<div class=\"timeline_date\">" + dateString + "</div>"
html += "<div class=\"timeline_nextmonth\" title=\"Next Month\"></div>"
html += "<div class=\"timeline_nextyear\" title=\"Next Year\"></div>"
this.placeHolders.arrows.append(html);
var children = this.placeHolders.arrows.children();
var self = this;
$(children[0]).bind("click", this, function () {
self.previousYear()
});
$(children[1]).bind("click", this, function () {
self.previousMonth()
});
$(children[3]).bind("click", this, function () {
self.nextMonth()
});
$(children[4]).bind("click", this, function () {
self.nextYear()
});
}
this.getEventsForDay = function (dayNumber) {
var result = [];
for (var i = 0; i < this.events.length; i++) {
var e = this.events[i];
if (e.day == dayNumber && e.month == this.date.getMonth() && e.year == this.date.getFullYear()) result.push(this.events[i]);
}
return result;
}
this.setupPlaceHolders = function () {
var arrows = jQuery(document.createElement("div"));
arrows.addClass("timeline_arrows");
var bottom = jQuery(document.createElement("div"));
bottom.addClass("timeline_bottom");
var top = jQuery(document.createElement("div"));
top.addClass("timeline_top");
top.append("<ul></ul>");
bottom.append("<ul></ul>");
this.container.append([arrows[0], top[0], bottom[0]]);
return {
arrows: arrows,
bottom: bottom.find("ul:first"),
top: top.find("ul:first")
};
}
this.getMonthRepresentation = function () {
var result = [];
var numberOfDays = this.getNumberOfDaysInMonth(this.date);
var firstDay = this.getFirstDayOfMonth(this.date);
var finished = false;
for (var i = 0; i < numberOfDays; i++) {
result.push({
name: this.weekDays[firstDay].substring(0, 3),
number: (i + 1 < 10) ? "0" + (i + 1) : (i + 1),
events: this.getEventsForDay(i + 1)
});
firstDay = (firstDay == 6) ? 0 : ++firstDay;
}
return result;
}
this.getNumberOfDaysInMonth = function (dateObject) {
var month = dateObject.getMonth();
if (month == 1) {
var leapYear = (new Date(dateObject.getYear(), 1, 29).getDate()) == 29;
if (leapYear) return 29
else return 28;
} else return this.daysPerMonth[month];
},
this.getFirstDayOfMonth = function (dateObject) {
var save = dateObject.getDate();
dateObject.setDate(1);
var result = dateObject.getDay();
dateObject.setDate(save);
return result;
},
this.isToday = function (dayNumber) {
var today = new Date();
return (today.getDate() == dayNumber && today.getFullYear() == this.date.getFullYear() && today.getMonth() == this.date.getMonth());
},
this.onMouseEnter = function (event) {
var left = $(event.target).offset().left;
var width = $(event.target).outerWidth();
this.bubble.setContent(event.data.events);
this.bubble.show(left + (width / 2));
}
this.onMouseLeave = function (event) {
this.bubble.hide();
}
this.nextMonth = function () {
this.date.setMonth(this.date.getMonth() + 1);
this.render();
}
this.nextYear = function () {
this.date.setYear(this.date.getFullYear() + 1);
this.render();
}
this.previousMonth = function () {
this.date.setMonth(this.date.getMonth() - 1);
this.render();
}
this.previousYear = function () {
this.date.setYear(this.date.getFullYear() - 1);
this.render();
}
this.initialize();
}
Timeline.Bubble = function (timeline) {
this.initialize = function () {
var IE6Class = (timeline.isIE6) ? " bubbleIE6" : "";
var id = "bubble_" + new Date().getTime();
var html = "";
html += "<div id=\"" + id + "\" class=\"timeline_bubble\">";
html += "<div class=\"bubble_top" + IE6Class + "\"></div>";
html += "<div class=\"bubble_mid" + IE6Class + "\"></div>";
html += "<div class=\"bubble_bottom" + IE6Class + "\"></div></div>";
timeline.container.after(html);
this.container = $("#" + id);
this.container.bind("mouseenter", this, this.onMouseEnter);
this.container.bind("mouseleave", this, this.onMouseLeave);
}
this.onMouseEnter = function (event) {
event.data.stopHiding();
}
this.onMouseLeave = function (event) {
event.data.hide();
}
this.stopHiding = function () {
if (this.goingOffHandle && this.goingOffHandle != null) {
clearTimeout(this.goingOffHandle);
this.goingOffHandle = null;
}
}
this.setContent = function (events) {
this.stopHiding();
var html = "";
for (var i = 0; i < events.length; i++)
html += "<div><div class=\"event_title\">" + events[i].name + "<p class=\"event_data\">" + events[i].content + "</p></div></div>";
var midSection = $(this.container.children()[1]);
midSection.empty();
midSection.append(html);
var titles = midSection.find(".event_title");
titles.each(function (inx, element) {
$(element).bind("mouseenter", function (event) {
$(element).children(":first").animate({
opacity: "toggle"
}, 200);
});
$(element).bind("mouseleave", function (event) {
$(element).children(":first").animate({
opacity: "hide"
}, 200);
});
});
}
this.show = function (at) {
this.container.animate({
opacity: "show"
}, 250);
this.container.animate({
left: at - (this.container.outerWidth() / 2)
}, 300);
}
this.hide = function () {
var self = this;
this.goingOffHandle = setTimeout(function () {
self.container.animate({
opacity: "hide"
}, 250);
}, 700);
}
this.initialize();
}
In this.renderDay try inverting the two .append lines :
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
so that it reads
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");

OOP JS: function incrementing date repeatedly, and I don't know why?

Following on from my previous thread, I went on to design the following Objects.
/* --- LEAP Namespace --- */
var LEAP = {};
/* --- LEAP.Schedule Object --- */
LEAP.Schedule = function(){//init
this.weeks = [];
this.calculateWeeks();
};
LEAP.Schedule.prototype.pad = function (n) {
return n>9 ? n : "0"+n;
};
LEAP.Schedule.prototype.calculateWeeks = function(){
this.date = new Date ( 2011, 8, 5 ); // First week of new school year
this.num = 36; // Calendar number of this week
this.weeks.push(new LEAP.Schedule.week(this.date, this.num));
for (var i = 1; i < 51; i++) {
var week = i * 7;
var updated_date = new Date ();
updated_date.setDate(this.date.getDate() + week);
if (this.num > 51) {
this.num = 0;
}
this.num++;
this.weeks.push(new LEAP.Schedule.week(updated_date, this.num));
}
};
LEAP.Schedule.prototype.getWeeks = function(){
return this.weeks;
};
/* --- LEAP.Schedule.week Object --- */
LEAP.Schedule.week = function(n_date, n_week){
this.week = n_week;
this.date = n_date;
this.year = this.date.getFullYear();
var JSMonth = this.date.getMonth();
JSMonth += 1;
this.month = JSMonth;
this.day = this.date.getDate();
};
LEAP.Schedule.week.prototype.getJSDate = function(){
return this.date;
};
LEAP.Schedule.week.prototype.getStartDate = function(){
return this.year + "-" + LEAP.Schedule.pad(this.month) + "-" + LEAP.Schedule.pad(this.day);
};
LEAP.Schedule.week.prototype.getEndDate = function(){
var EndOfWeek = this.date;
EndOfWeek.setDate(this.date.getDate() + 6);
var year = EndOfWeek.getFullYear();
var month = LEAP.Schedule.pad(EndOfWeek.getMonth() + 1);
var day = LEAP.Schedule.pad(EndOfWeek.getDate());
return year + "-" + month + "-" + day;
};
LEAP.Schedule.week.prototype.getLabel = function(){
return "Week " + this.week + ": " + this.day + (this.day==1||this.day==21||this.day==31?"st":this.day==2||this.day==22?"nd":this.day==3||this.day==23?"rd":"th") + " " + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][this.month-1] + " " + this.year;
};
I'm now using a <SELECT> box to filter some other data, which works successfully, apart from the fact that every time the $('#filter').change() event is triggered, the dates are being incremented.
WeeklyUpdate.init = function() {
UWA.Data.getJson(WeeklyUpdate.URL + "?cmd=getPointTotals", WeeklyUpdate.getTotalPoints);
var Scheduleobject = new LEAP.Schedule();
var weeks = Scheduleobject.getWeeks();
WeeklyUpdate.displayWeekFilter(weeks);
}
WeeklyUpdate.displayWeekFilter = function(weeks) {
var WeekFilterDisplayHTML = '<select id="filter"><option>Click here</option><option value="all">- All, to date</option>';
var now = new Date();
for (var i = 0; i < weeks.length; i++) {
if (weeks[i].getJSDate() < now) {
var label = weeks[i].getLabel();
WeekFilterDisplayHTML += '<option value="' + i + '">' + label + '</option>';
}
}
WeekFilterDisplayHTML += '</select>';
$('div#filter').html(WeekFilterDisplayHTML);
//WeeklyUpdate.filterPointTotalsByStaff( $(this).val() )
$("select#filter").change( function() { WeeklyUpdate.filterPointTotalsByStaff( weeks, $(this).val() ) } );
}
WeeklyUpdate.filterPointTotalsByStaff = function(weeks, val) {
if (val >= 0 && val != "all") {
var StartDate = weeks[val].getStartDate();
var EndDate = weeks[val].getEndDate();
If I add alert(StartDate + ' // ' + EndDate); after those variables, I can see that the EndDate is being incremented every time, rather than being incremented once and then consistently returning the correct EndDate regardless of how many times it is selected from the SELECT box. The StartDate on the other hand works correctly every time.
What should happen is that this.date (which returns a JS date Object for the week being requested) should be the start of the week, then the getEndDate() function should increment that date by 6 days and return the correct date in a MySQL-compatible format. This shouldn't increment every time its <OPTION> is selected from the SELECT box; it should always return the same date.
I'm guessing that it's something to do with the way I've used EndOfWeek = this.date;, but I don't understand why or how.
Many thanks again.
Probably doesn't matter here but is bad form anyway:
for (i = 1; i < 51; i++) {
The variable i should be declared.
In the statement (my wrapping):
$("select#filter").change( function() {
WeeklyUpdate.filterPointTotalsByStaff( weeks, $(this).val() )
});
You do not show how weeks is initialised or assigned a value. There is a weeks property of LEAP.Schedule instances, but above it is used in the context of a global variable.

how to get current time without using system time...?

Is it possible to get it through javascript?
You can get the current time from the web server, from the local machine, or by calling a web service. While that last choice is possible, it would be the slowest and least performant.
<script type="text/javascript">
var d_names = new Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var d = new Date();
var curr_day = d.getDay();
var curr_date = d.getDate();
var sup = "";
if (curr_date == 1 || curr_date == 21 || curr_date ==31)
{
sup = "st";
}
else if (curr_date == 2 || curr_date == 22)
{
sup = "nd";
}
else if (curr_date == 3 || curr_date == 23)
{
sup = "rd";
}
else
{
sup = "th";
}
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
console.log(d_names[curr_day] + " " + curr_date + "<SUP>"
+ sup + "</SUP> " + m_names[curr_month] + " " + curr_year);
</script>
This is how you get the values through javascript. Not sure what you mean by without using system time
From http://www.webdevelopersnotes.com/tips/html/formatting_time_using_javascript.php3
<script type="text/javascript">
<!--
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
{
a_p = "AM";
}
else
{
a_p = "PM";
}
if (curr_hour == 0)
{
curr_hour = 12;
}
if (curr_hour > 12)
{
curr_hour = curr_hour - 12;
}
var curr_min = d.getMinutes();
document.write(curr_hour + " : " + curr_min + " " + a_p);
//-->
</script>

Categories