Add class to element based on date - javascript

I have a span element that looks like this.
html
<span class="tribe-event-date-start">September 5 # 7:00 pm</span>
I would like to target that element by its date and add a class to its parent container.
The class is intended to highlight the container if the current date matches the date in the element. Note, I can only get the Month and Day here, so that's all that needs to match. I am not a JS or JQuery expert at all, but get the basics, I know I can utilize one of the two to produce the end result.
This is the output of the WordPress plugin "The Events Calendar" widget to display upcoming events.
The end result should be a class added to the parent div IF the element date matches the actual day's date.

If you can trust the output will always look like that you can do something like:
var _dateToCheck = $(".tribe-event-date-start").text();
_dateToCheck = _dateToCheck.substring(0,_dateToCheck.indexOf("#"));
_dateToCheck.trim();
var _current = new Date();
console.log(_dateToCheck.getMonth(), _dateToCheck.getDate(), _current .getMonth(), _current.getDate());
so then you can do your comparison checks against the month, then followed by the date.
If that class "tribe-event-date-start" is actually what needs to be applied to the element, then you would do that after your date comparison logic... but you still need something to seach on, so if you don't have a class or an ID to start with then you're going to have to use the actual element, but I'd still try and whittle that list down a bit - something like:
var _allTheRows = $("#my-calendar-plugin-thing span");
_allTheRows.each(checkDate);
function checkDate(el){
var _dateToCheck = $(el).text();
_dateToCheck = _dateToCheck.substring(0,_dateToCheck.indexOf("#"));
_dateToCheck.trim();
var _current = new Date();
console.log(_dateToCheck.getMonth(), _dateToCheck.getDate(), _current
.getMonth(), _current.getDate());
//... check if date is greater or smaller or the same, or whatever your logic is
if(meetsMyCondition){$(el).parent().addClass("tribe-event-date-star")}
}

Related

Full Calendar Get current date

I've been learning Ruby over the last year and I'm very new to JS so I'll try to explain this as best I can.
I am using Adam Shaw's full calendar plugin. All I want to do is get the current month I am viewing (and use that to limit how far in the future or past a user can navigate, but that's not the problem).
I can get the current date, sort of. But, because of my lack of JS knowledge I'm not sure how to access the date.
Here is the relevant section of the config file,
viewRender: function(view){
var maxDate = "<%= finish.strftime('%Y/%m/%d') %>";
var currentDate = $('#calendar').fullCalendar('getDate');
console.log(currentDate);
if (view.start > maxDate){
header.disableButton('prev');
}
}
When I inspect the console log I see this being output as I click through the months.
So as you can see it is displaying the current date in view. My question is how do I access the _d bit of the Moment variable so I can use it?
My understanding would be that the Moment is class instance and the stuff in the dropdown is like its attributes, would this be a correct interpretation?
To get the current date of the calendar, do:
var tglCurrent = $('#YourCalendar').fullCalendar('getDate');
This will return the date as a moment object. You can then format it as a string in the usual date format like so:
var tgl=moment(tglCurrent).format('YYYY-MM-DD');
For the actual time, use the format: YYYY-MM-DD LTS
FullCalendar's getDate returns a moment object, so you need moment's toDate() method to get date out of it.
So, in you code try:
console.log(currentDate.toDate());
and that should return a date object.
var moment = $('#YourCalendar').fullCalendar('getDate');
var calDate = moment.format('DD.MM.YYYY HH:mm'); //Here you can format your Date

Add days to user inputed date in Javascript

So I've run into a snag trying to make a date calculator in Javascript. I'm fairly new to Javascript so I feel like I'm diving in a little deep, but here's a rundown of what I'm trying to accomplish.
Here's a jsfiddle: http://jsfiddle.net/b52hamw7/2/
I first have a form in my HTML formatted as follows:
<form>
<p class="instructions">I need my items by:</p><br>
<input type="date" name="date" value="" id="date"/>
<input type="button" value="Submit" id="submit">
</form>
<p>Be sure to order by:</p><p id="dateoutput"></p>
The idea here is that a user will input a date into the form and then a javascript code will add 10 days to it and output the day that they need to order by, formatted as a date.
Here's the script that I have so far, which I know isn't close to working, but it's a start I guess:
<script>
document.getElementsByName("submit").onclick = function() {
var dateIn = document.getElementsById("date").value;
var addDays = 10;
var dateOut = dateIn + addDays;
};
document.getElementById("dateoutput").innerHTML = dateOut;
</script>
I really appreciate any direction you can give me on this one. Thanks in advance!
There are multiple typos and issues in your code. I will list some of them below to get you on the right track.
1) Your line document.getElementsByName("submit").onclick.... is attempting to search for an element with name="submit" of which you have none in your HTML.
2) The next line var dateIn = document.getElementsById("date").value; has a typo, it should be: document.getElementById("date").value. You have an extra 's'.
3) The line document.getElementsById("dateoutput").innerHTML = dateOut; has 3 problems. First you have the extra 's' as in point 2 above. Second, you are attempting to assign the innerHTML to the value of variable that you have lost scope for. And Finally it is not executed within the context of the click function and is executed immediately when it is parsed as opposed to when the click event occurs. Therefore it needs to be moved within your onclick handler function.
4) With respect to adding days to the date. Please check out Add days to JavaScript Date. Right now you are attempting to to add 10 to a string value that you are pulling from the input element which simply concatenates the string '10' onto the end of your date string. You need to convert it to a date object and then add the 10 days. This is explained in code examples in the link provided

jQuery function only being run once

Using the Moments.js library I'm attempting to grab the value of the datetime attribute from every time tag and output the time using natural language.
Given this:
<time datetime="2014-06-27"></time>
The Results would be:
<time datetime="2014-06-11">17 hours ago</time>
Using this:
$(document).ready(function(){
var time = $('time'),
date = moment(time.attr('datetime')),
update = function(){
time.html(date.fromNow());
};
update();
});
It works, but only for the first time element. All the additional time elements are also saying "17 hours ago".
It's my guess that the function is only being run once on the first instance of time.
How can I make sure it's being run for each, and doing so efficiently?
You need to loop through all the time tags. Right now you are only applying it to the first instance of <time>. Use jQuery .each().
$(document).ready(function(){
var time = $('time');
time.each(function() {
date = moment($(this).attr('datetime'));
$(this).html(date.fromNow());
});
});
jsFiddle Demo

JQuery Datepicker change value attribute of div when current date is selected

The jQuery Datepicker is working great, but I would like the submit button to read different text based on whether or not the day selected is today. The submit button is a <button> and the text is the value attribute.
Is there any way to do this? My web searches haven't turned up any results.
Try like below
var dp = $('#datepicker').datepicker("getDate");
1) using the above statement, you can get the date that has be selected in datepicker (ie., parsed as date datatype)
2) Using date.toDateString(), you can get the date string which can be used to compare with datepicker's date.
$('#datepicker').datepicker();
$('button').on('click', function () {
var dp = $('#datepicker').datepicker("getDate");
var today = new Date();
if (today.toDateString() == dp.toDateString()) {
//write your code to change the text in div
}
});
FYI: value attribute is not associated with div element, I guess you're referring to custom data* value attribute.
If so then you can change it using .data() method of jQuery. Example
$('div').data('value', 'whatever you wish');
JSFiddle
If I Understood your question correctly, You want to make sure that date picked is today or not, upon submission of form.
I've gone through google, ended up with an answer, Hope It work out.
function ValidRange(date1)
{
var date=new date(); //Today
//Convert these dates into milliseconds
var date1_ms=date1.getTime();
var date_ms=date.getTime();
//Calculate difference between them
var difference_ms = date_ms - date1_ms;
return difference_ms; // It will return 0 if date is today.
}
Note: You then need to parse the strings you are getting from the UI, with Date.parse, like this:
ValidRange(Date.parse(Date_Picked));
Try this.

JavaScript <div> .class Extraction

I am writing JavaScript that retrieves a webpage from another site, and only displays 'Notices' from a site.
Fortunately, all 'Notices' are div elements of class 'event'.
I want to extract only these divs from the returned code so that I can re-format and display them. All the code I have so far is working, but I'm not sure on how to extract the 'event' divs from the source code. Any ideas?
function getNotices(){
// Get the date from the form
var str = document.getElementById('formDate').value;
var year = str.slice(1,4); // Extract Year
var month = str.slice(6,7); // Extract Month
var day = str.slice(9,10); // Extract Day
// Inject correct date into URL
var link = "Raw Link";
// Write raw link to div for debugging
document.getElementById('rawLink').innerHTML = link; (debugging)
// Bounce off anyorigin.com to get the source
// Re-inject date into new link
var anyLink = "http://anyorigin.com/get?url=http%3A//ilearn.stpauls.school.nz/calendar/view.php%3Fview%3Dday%26course%3D%26cal_d%3D" + day + "%26cal_m%3D" + month + "%26cal_y%3D" + year + "&callback=?"; // Splice the date into the school link and site to bounce it off
$.getJSON('http://anyorigin.com/get?url=http%3A//ilearn.stpauls.school.nz/calendar/view.php%3Fview%3Dday%26course%3D1%26cal_d%3D30%26cal_m%3D7%26cal_y%3D2013&callback=?', function(data){
var obj = JSON.stringify(data); // Turn object into a string
document.getElementById('hopefullyTheData').innerHTML = obj; // Print string containing SPC website onto page (debugging)
});
}
Thanks guys!
Load the contents into jQuery then select by event class:
var events = $(data.contents).find('.event');
You can append only the event nodes by searching inside data.contents:
$('.event', data.contents).appendTo('#hopefullyTheData');
use $('div.event') selector to extract all the div element having class event.

Categories

Resources