Select current date on calendar with javascript and html - javascript

I created a simple calendar with html and now want the current date to highlight automatically with javascript. I know of a few ways to do this but I am looking for the most simple.

It really depends on how your calendar works. You can get the client's current date with the following JavaScript:
var currentDate = new Date();
Once you have that, you'll have to use the built in date functions to get the current date element and probably add a class to it that will style it as highlighted.
UPDATE
Assuming you have your li elements with id="dayElement_x" where x is the day number, and your class for highlighting your day is currentDay, an example JavaScript call would be:
document.getElementById('dayElement_' + (new Date()).getDate()).className += ' currentDay';
UPDATE 2
I just thought of a solution where you can do this without having a bunch of ids. Here is the JavaScript:
document.getElementById('calendarContainer').
getElementsByTagName('li')[(new Date()).getDate() - 1].className += ' currentDate';

Related

Full Calendar - How to add leading zeros to the days in Month View of Full Calendar

I want to add leading Zeros to these single digit days in FullCalendar month view.
What I want is :
Means, 3 as 03, 4 as 04 and so on..
Years later I could not find an option to set the day-number format to one with a leading zero, i did it the same way but without JavaScript in Fullcalendar 5.4.0:
The classname in my case was .fc-daygrid-day-number, I think thats implements the type of the initialized view, whats in my case initialized with: {initialView: 'dayGridMonth'}
Array.prototype.forEach.call(
document.querySelectorAll('.fc-daygrid-day-number'),
function(el) {
if (el.innerText.length === 1) {
el.innerText = '0' + el.innerText;
}
}
)
There doesn't appear to be an option for this in the fullCalendar options curently. Without modifying the fullCalendar source, the best I could come up with is this. If you look at the rendered calendar HTML, you'll see that each day number is wrapped in a <td> with the CSS class fc-day-number. So we can modify the contents of the <td>. Put this code directly after your calendar initialisation code:
$('.fc-day-number').each(function() {
var day = $(this).html(); //get the contents of the td
//for any fields where the content is one character long, add a leading zero
if (day.length == 1)
{
$(this).html("0" + day);
}
});
I had the same problem with React and find this question equivalent. Then I come up with this solution at Fullcalendar 5.6.0:
I used a prop called "dayCellContent" and passed a function to return the formatted string.
<FullCalendar
plugins={[dayGridPlugin]}
initialView="dayGridMonth"
dayCellContent={({ dayNumberText }) => (("00" + dayNumberText).substring(dayNumberText.length))}
/>

create 'time finishing' from value

I have a countdown timer in jQuery with a pause/resume function.
I'd like to take the "totalSeconds" value and add it to the current time so that I can display what time the countdown will finish...
so it'd be "current time" + "totalSeconds" on the page load(?)
How would you calculate this and create the <p> tag with jQuery?
The below code would append the <p> element to the end of the body tag.
If you want to format the date, you could use this jquery plugin, or some simple string manipulation.
var totalSeconds = 300;
var date = new Date();
date.setSeconds(date.getSeconds() + totalSeconds);
$("body").append("<p>"+date+"</p>");

JavaScript - Input a date then autopopulate next field with difference

Hi this is making me nuts. I am not a developer. Trying to get this to work.
User puts in a date (hire date) into form using Date object (calendar)
Next field should take that date and subtract todays date to get the length of employment.
But I get undefined in the field AND my original hire date disappears.
Here is what I have, help please, much appreciation!
//grab date of hire
try{document.getElementById("dData_DOH").onchange = custom_calculateDate;}catch(e){}
//not sure if necessary - field that the difference should go to
try{document.getElementById("dData_LengthEmp").onblur = insertDate;}catch(e){}
//Function to grab input hire date
//Create variable for now
//Create variable for difference
function custom_calculateDate(){
var hireDate = document.getElementById("dData_DOH").value = "";
var timeNow= new Date();
var diff = Math.abs(timeNow - hireDate);
document.getElementById("dData_DOH").setAttribute('value', custom_calculateDate());
}
//Function to get the difference into the LengthEmp field
function insertDate() {
document.getElementById("dData_LengthEmp").setAttribute("", custom_calculateDate());
}
I know this is completely wrong, as I said I am not a developer or programmer, I cannot figure out how to get this information into this field and get my original field to still show.
Thank you for reading this!
Use value instead of setAttribute
document.getElementById("dData_DOH").value = custom_calculateDate();
Wow wow wow.
I'll try to rewrite your code by giving you explainations about why:
// Firstly, the onchange event doesn't work on IE for text inputs, prefer onblur
document.getElementById('dData_DOH').onblur = function(e) {
// Now let's get some variables
var hireDate = this.value, // "this" refers to the element that triggered the event
now = new Date(),
// You were on the right track for the difference, almost!
diff = Math.abs(new Date(now.getTime() - hireDate.getTime()))
// Finally, just don't change the original field, but the one you wanted to modify
document.getElementById('dData_LengthEmp').value = diff.toTimeString() // Get the time as a readable format
}
I haven't tested the solution, but it should get you on the track.
Btw, don't use try/catch.

jQuery Slideshow from XML with date parameters

So I have been tasked with creating a jQuery slideshow from an XML file with a timing mechanism to change the images based on date. I have the slideshow working from the XML, but I am struggling with adding the date feature. I would like to be able to "turn on" and "turn off" images based on the onDate and offDate. I understand Javascript is not the best way to show things based on date, but there are limits within the current site structure that prevent server side timing. So I would like to have the ability to load up say 10 images, and then only show three based on what today's date is, and what the onDate/offDate are.
This is the logic I was thinking.... If today is < onDate .hide or if today is > offDate .hide else .show
Where I am struggling
The correct way to enter the date in the XML file.
Parsing the date from XML into something that Javascript and in turn jQuery can use to compare today's date with the date in XML and show the image accordingly.
Once the date has been established figuring out a way to show or hide the specific image based on date.
Any help would be greatly appreciated.
XML
<eq-banner>
<id>1</id>
<url>linktopage.html</url>
<img>image.jpg</img>
<dept>equipment</dept>
<onDate>12/01/2010</onDate>
<offDate>12/31/2010</offDate>
<copy>FREE Stuff</copy>
</eq-banner>
jQuery
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "rotationData.xml",
dataType: "xml",
success: xmlParser
});
});
function xmlParser(equipment) {
$(equipment).find('eq-banner').each(function() {
var id = $(this).attr('id');
var dept = $(this).find('dept').text();
var url = $(this).find('url').text();
var img = $(this).find('img').text();
$('<div class="'+dept+'"</div>').html('<img src="images/'+img+'" /><br />').appendTo('#apparel')
$("#equipment").cycle({
fx:"fade",
speed:100,
timeout:5000
});;
});
}
</script>
HTML
<div id="equipment">
</div>
If you trust the data quality of the XML source, specifically that the dates are all well-formed as in your sample, it's pretty easy to turn that into a JavaScript "Date" object:
var str = "12/31/2010";
var pieces = str.split('/');
var date = new Date(~~str[2], ~~str[0] - 1, ~~str[1]);
(The ~~ trick converts the strings to numbers; do that however you prefer.) Also months are numbered from zero, and hence the subtraction.
Comparing dates works perfectly well in JavaScript, or you can call the ".getTime()" method on a date to explicitly get a "milliseconds since the epoch" value to compare instead.
As to how you'd show/hide the images, I'd be inclined to conditionally add a class to elements to be hidden (or shown; whichever makes the most sense).
XML doesn't have a "correct" way of handling dates, and JavaScript can parse just about anything. However, the most JS-friendly format would be something like "October 20, 2011" with the time optionally added in "12:34:56" format. A string like that can be fed directly to the new Date() constructor and be parsed correctly regardless of location.
datestr = "October 20, 2011";
date = new Date(datestr);
To compare Date objects, just use < or > -- however, a JS Date object contains a time element which will also be compared. So if you create a new Date object for the present with var now = new Date(); and compare it to var dat = new Date("string with today's date"); you'll find that dat is less than now because dat has time 00:00:00 while now has the present time. If this is a problem, you'll have to explicitly compare Date.getDate(), Date.getMonth() and Date.getFullYear() all at once. ( http://www.w3schools.com/jsref/jsref_obj_date.asp )

manipulating date object with javascript

i have been tinkering with the date object.
I want to add a dynamic amount of days to a day and then get the resulting date as a variable and post it to a form.
var startDate = $('#StartDate').datepicker("getDate");
var change = $('#numnights').val();
alert(change);
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + change);
does everything correctly except the last part. it doesnt add the days onto the day
take this scenario:
startdate = 2011-03-01
change = 1
alert change = 1
endDate = 2011-03-11 *it should be 2011-03-02*
thank you to all the quick replies.
converting change variable to an integer did the trick. thank you.
parseInt(change)
just to extend on this: is there a way to assign a variable a type, such as var charge(int)?
You may have fallen victim to string concatenation.
Try changing your last parameter in the Date constructor to: startDate.getDate() + parseInt(change)
See this example for future reference.
convert change to a number before adding it. it looks like you're getting a string concatenation operation rather than the addition you're expectingin your code.
I believe you are concatenating instead of using the mathematical operator. Try this instead,
var endDate = new Date(startDate.getFullYear(), startDate.getMonth(),startDate.getDate() + (+change));
It looks like you are not adding the ending day, you are concatinating it so '1' + '1' = '11'
use parseInt() to make sure you are working with integers
example
var change = parseInt($('selector').val());
Also, with this solution, you could easily end up with a day out of range if you are say on a start date of the 29th of the month and get a change of 5

Categories