I want to be able to set up HTML pages and load them into a single home page. Each html file will be named as the date (eg 03052016.html for today) and then the correct html will be pulled in each day on the homepage.
However not all days will have a html file, in which case it should roll back to a previous day. I have successfully loaded the page, nice and easy but can't work out a way to identify that the page hasn't loaded and subtract one from the day. My current attempt is the following:
<body>
<div id="success"></div>
<script>
//section creates the html file name for today
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
var today = "05052016.html";
//do loop to subtract days until file is found
do{
var found = true; //variable records file presence
$( "#success" ).load( today, function( response, status, xhr ) {
if ( status == "error" ) {
var found = false;
if(parseInt(dd)>1){
dd = parseInt(dd)-1;
}else {
mm = parseInt(mm)-1;
dd = 30 //will deal with 31/30/28 day months later.
}
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
//
console.log( msg + xhr.status + " " + xhr.statusText );
}
});
}until(found == false )
</script>
I am new to web authoring so please be brutal if I am way off how to implement this. It seems so easy but the loop just won't work!
I am currently testing in FireFox, and using jquery-1.10.2.js
check de length of the content of the quuestioned div.
var div = $('div');
var dHtml = div.html();
var long = dHtml.length;
if(long > 0)
{
//do stuff
}
You need to understand that ajax (which is behind load) is asynchronous so you cannot test the found outside the success.
Try this:
function pad(num) {return String("0"+num).slice(-2)}
function getFilename(date)
var dd = pad(date.getDate());
var mm = pad(date.getMonth()+1); //January is 0!
var yyyy = date.getFullYear();
return ""+dd+mm+yyyy+".html";
}
var date = new Date(),
aDay = 10*24*60*60*1000,
giveUp = new Date(date.getTime()-(10*aDay)); // max 10 days back
function loadFile(date) {
$("#success").load( getFilename(date), function() {
if (status == "error") {
if (date>giveUp) {
date.setDate(date.getDate()-1)
loadFile(date);
}
}
});
}
$(function() {
loadFile(date);
});
Related
I have a website with multiple pages (http://www.europarl.europa.eu/sides/getDoc.do?type=PV&reference=20190131&secondRef=TOC&language=EN)
I crawled each page and got links with minutes in it. Each link with minutes has a date, after I created folders with Years and Months, I stuck with a store files from links.
The question is:
How can I download links in a month directory?
function crawlLink(link){
link = 'http://www.europarl.europa.eu'+link;
request(link, (error,response,
html) => {
if (!error && response.statusCode == 200) {
const $ = cheerio.load(html);
const docTitle = $('.doc_title' ) ;
var str = docTitle.html();
var date_str = str.replace(' - Brussels','').replace(' - Strasbourg', '');
var date = new Date(date_str);
console.log("created new dateobj", date);
var year = new Array('January','February', 'March' , 'April' , 'May' , 'June', 'July' ,'August','September','Oktober','November','December');
var mm = date.getMonth(); //January is 0
var yyyy = date.getFullYear();
var monthName = year[mm];
var yearDir = './data/'+yyyy;
if (!fs.existsSync(yearDir)){
fs.mkdirSync(yearDir);
}else{
console.log('yearDir exists');
}
var monthDir = yearDir+'/'+monthName;
if (!fs.existsSync(monthDir)){
fs.mkdirSync(monthDir);
}else{
console.log('monthDir exists');
}
console.log("wouhu everything is fine, get links and download them to monthDir");
let downloadLinks = [];
let $links = $('.doc_formats_box a');
$links.each(function(i, elem) {
downloadLinks.push({
title:$(this).text(),
link:$(this).attr('href')
});
});
console.log(downloadLinks);
`
In my project - which is a App, I have multiple datepicker which is Version 2.0. My Client wants me to customise my datepicker by showing the date of the calendar top, so I did some tweaks, it is working on the page with one datepicker but it's an another story when it comes to multiple datepicekers on one page.my code is as follows.
$(elem).datepicker(options);
//Customized Datepicker Plugin 03/07/2017
//Author - Jithin Raj
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$(elem).on('show', function() {
var cPicVal = '',
yPicVal = '';
if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
$('.datepicker-dropdown').prepend('<div class="new-date-wrap"><div class="custom-year-pic-view"><span></span></div><div class="custom-day-pic-view"><span></span></div></div>');
}
if ($(elem).val() == '') {
cPicVal = (Date.parse(today).toString('ddd, MMM dd'));
yPicVal = (Date.parse(today).toString('yyyy'));
} else {
cPicVal = (Date.parse($(elem).val()).toString('ddd, MMM dd'));
yPicVal = (Date.parse($(elem).val()).toString('yyyy'));
}
$('.custom-day-pic-view').find('span').text(cPicVal);
$('.custom-year-pic-view').find('span').text(yPicVal);
});
});
Can anyone suggest me a another fullprofe method, thankyou Cheers..
I think I found an answer.
I changed my code a little bit and added moment.js and now it's working all over my app.
$(elem).datepicker(options);
//Customized Datepicker Plugin 03/07/2017
//Author - Jithin Raj
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$(elem).on('show', function() {
var cPicVal = '',
yPicVal = '';
elem = $(this)
if ($('.datepicker-dropdown').find('.new-date-wrap').length <= 0) {
$('.datepicker-dropdown').prepend('<div class="row-fluid new-date-wrap"><div class="row-fluid custom-year-pic-view"><span></span></div><div class="row-fluid custom-day-pic-view"><span></span></div></div>');
}
if ($(elem).val() == '') {
cPicVal = (moment(today).format('ddd, MMM DD'));
yPicVal = (moment(today).format('YYYY'));
} else {
cPicVal = (moment($(elem).val()).format('ddd, MMM DD'));
yPicVal = (moment($(elem).val()).format('YYYY'));
}
$('.custom-day-pic-view').find('span').text(cPicVal);
$('.custom-year-pic-view').find('span').text(yPicVal);
});
I using a date-picker to set a start and end date. The date range is supposed to move forward each day for a two week, sliding window of entry.
My code below works but I would like to refactor it into something that is easier to maintain. What techniques or tools can I use to improve this code?
var challenge_start = new Date(2015,04,04);
var challenge_end = new Date(2015,06,12);
var range_start;
var range_end;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(today<challenge_start) {
range_start=challenge_start;
range_end=challenge_start;
}
else if(today>challenge_start && today<challenge_end) {
if(mm==5) {
if(dd<18) {
range_start=challenge_start;
range_end=today;
}
else {
range_start=today.setDate(today.getDate()-14);
range_end=today;
}
}
else if(mm=6) {
if(dd<29) {
range_start=today.setDate(today.getDate()-14);
range_end=today;
}
else {
range_start=today.setDate(today.getDate()-14);
range_end=challenge_end;
}
}
else if(mm==7) {
if(dd<12) {
range_start=today.setDate(today.getDate()-14);
range_end=challenge_end;
}
else {
range_start=challenge_end;
range_end=challenge_end;
}
}
}
else if(today>challenge_end) {
range_start=challenge_end;
range_end=challenge_end;
}
$("#date").datepicker({
startDate: range_start,
endDate: range_end,
keyboardNavigation: false,
autoclose: true,
todayHighlight: true,
language: langdate,
disableTouchKeyboard: true
});
I may not understand what you are striving for, but I'm pretty sure you don't need to have those if(mm==x) and if(dd=x) statements.
Perhaps this is what you want:
var challenge_start = new Date(2015,04,04);
var challenge_end = new Date(2015,06,12);
function getDatePlusDays(origDate, days) {
var date = new Date(origDate.getTime());
date.setDate(date.getDate() + days);
return date;
}
function getClosestDateInRange(startDate, endDate, date) {
return (date < startDate) ? startDate
: ((date > endDate) ? endDate: date);
}
var today = new Date();
var range_start = getClosestDateInRange(challenge_start, challenge_end, getDatePlusDays(today, -14));
var range_end = getClosestDateInRange(challenge_start, challenge_end, today);
jsfiddle
I'm trying to make a site that displays a different line of text depending on the hour (GMT). I have tried using javascript, but I'm very much a beginner! I've managed to piece the following bit of code together but can't seem to get it to work. Any help appreciated!
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11)
{
document.write("<b>Paris</b>");
}
;
});
Javascript has a Date class.
var hour = new Date().getHours();
if(...) {
// do something
}
This code extract
if (hour>10 && hour<11)
can't be working with hours, because time can't be > 10 and < 11 at the same time (hour is an int).
How about:
var now = new Date();
var utcMillis = now.getTime() + now.getTimzoneOffset() * 60000;
var hour = new Date(utcMillis).getHours(); // 0-23
switch(hour) {
case 10: document.write("<b>Paris</b>"); break;
//...
}
Some good info here: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
You could also put your phrases in an array (which you might get from the server):
var phrases = ["Hi!", "blah", "more blah", ...];
... and then you can replace the switch above with:
document.write("<b>" + phrases[hour] + "</b>");
You might want to save yourself some time and use a framework that makes things work pretty much the same way across different browsers. JQuery is my favorite, but there are plenty. Such libraries make it easy to manipulate content in your page, fetch JSON from the server, etc etc.
At first sight:
o.datetime is wrong formatted for JS Date method.
you return an instance of new Date() to get the hour use .getHours()
You can look here to find a way to convert your dateString from o.datetime How can I convert string to datetime with format specification in JavaScript?
Use time.getHours() > 12 instead of time > 12
If you use: getDateFromFormat() from http://www.mattkruse.com/javascript/date/ I think the conversion will be something like E, dd MMM hh:mm:ss +0000
SIMPLE ANSWER:
You can just parse the hour to your callback: (See your JSON here http://json-time.appspot.com/time.json?tz=GMT)
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(o.hour); // See o.hour here
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
if (time>10 && time<11) {
document.write("<b>Paris</b>");
}
});
I've created a quick jsfiddle page: http://jsfiddle.net/eBAGS/5/ with a demo that should do what you need. It gets the time from the users PC rather than from a server though, but it could be modified.
HTML
<button onClick="getPhrase()">Show me a phrase for this hour</button>
<div id="placeHolder"></div>
Javascript
function getPhrase() {
h = new Date().getHours(); //Get the current hour
phrase = new Array(); //Create an array of phrases
phrase[1] = 'Hello';
phrase[2] = 'there';
phrase[3] = 'this';
phrase[4] = 'will';
phrase[5] = 'show';
phrase[6] = 'a';
phrase[7] = 'different';
phrase[8] = 'message';
phrase[9] = 'depending';
phrase[10] = 'on';
phrase[11] = 'the';
phrase[12] = 'hour';
phrase[13] = 'of';
phrase[14] = 'day';
phrase[15] = 'that';
phrase[16] = 'you';
phrase[17] = 'look';
phrase[18] = 'at';
phrase[19] = 'it';
phrase[20] = '!';
phrase[21] = 'W';
phrase[22] = 'X';
phrase[23] = 'Y';
phrase[24] = 'Z';
document.getElementById('placeHolder').innerHTML = phrase[h-1]; //Show the array item relevant to the hour
}
I have this code that updates a calendar widget and input field, while validating the date. We want the user to be able to input any type of m-d-y format (m.d.y, m-d-y, and so on). The problem is the YUI calendar widget only accepts the m/d/y format. All others it returns as NaN. I have tried a couple ways to format the date, but can't get anything that seems to work. I would like to be able to do this with out a lot of overblown code. Does anyone have any suggestions as to the best approach here? Here is my code:
//CALENDAR --------------------------------------------------------------------------------
var initCal = function(calendarContainer){
if(YAHOO.env.getVersion("calendar")){
var txtDate = Dom.get("dateOfLoss");
var myDate = new Date();
var day = myDate.getDate();
var month = myDate.getMonth() +1;
var year = myDate.getFullYear() -1;
var newDate = month + "/" + day + "/" + year;
function handleSelect(type, args, obj){
var dates = args[0];
var date = dates[0];
var year = date[0], month = date[1], day = date[2];
txtDate.value = month + "/" + day + "/" + year;
aCal.hide();
}
function updateCal(){
if (!(txtDate.value.match(/((\d{2})|(\d))\/|\-((\d{2})|(\d))\/|\-((\d{4})|(\d{2}))/))) {
alert("Enter date in mm/dd/yy or mm/dd/yyyy format.");
}
else {
if (txtDate.value != "") {
aCal.select(txtDate.value);
var selectedDates = aCal.getSelectedDates();
if (selectedDates.length > 0) {
var firstDate = selectedDates[0];
aCal.cfg.setProperty("pagedate", (firstDate.getMonth() + 1) + "/" + firstDate.getFullYear());
aCal.render();
}
else {
alert("Date of Loss must be within the past year.");
}
}
}
}
var aCal = new YAHOO.widget.Calendar(null, calendarContainer, {
mindate: newDate,
maxdate: new Date(),
title: "Select Date",
close: true
});
aCal.selectEvent.subscribe(handleSelect, aCal, true);
aCal.render();
Event.addListener("update", "click", updateCal);
Event.addListener(txtDate, "change", function(e){
updateCal();
});
// Listener to show the 1-up Calendar when the button is clicked
// Hide Calendar if we click anywhere in the document other than the calendar
Event.on(document, "click", function(e){
var el = Event.getTarget(e);
if(Dom.hasClass(el, "calendarButton"))
aCal.show();
else if (Dom.hasClass(el, "link-close") || !Dom.isAncestor(calendarContainer, el))
aCal.hide();
});
}
else {
var successHandler = function() {
initCal(calendarContainer);
};
OURPLACE.loadComponent("calendar", successHandler);
}
};
Did you tried http://www.datejs.com/?
Maybe you can define some patterns and test agaist the input.
How can I convert string to datetime with format specification in JavaScript?
var updateCal = function(){
if (!(txtDate.value.match(/^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\d\d+$/))) {
return;
}
//else if ((txtDate.value.match(/^(0?[1-9]|1[012])[- .](0?[1-9]|[12][0-9]|3[01])[- .]\d\d+$/))) {
//}
else {
var changedDate = txtDate.value;
changedDate = changedDate.replace(/[. -]/g, "/");
txtDate.value = changedDate;
badClaimDate = claimDateWithinPastYear();
aCal.select(changedDate);
I used a RegEx to determine which, if any, delimiters needed to be replaced and simply used .replace.