jQuery function only being run once - javascript

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

Related

Add class to element based on date

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")}
}

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

Need to include the parameter in javascript url in htmls

I have an requirement where I need to pass the parameter dynamically in script url.
Example:
"<" script src="myfile.js" "><"/script>"
now I need to pass the timestamp in the src like
"<"script src="myfile.js?tm=12345"><"/script">"
so whenever the this html load it should always take the new timestamp and pass in to the url.
"<"script src="myfile.js?tm=6788"><"/script">"
I would really appreciate in case some can help me to find the solution to this problem.
You can do something like this:
var elem = document.createElement('script');
elem.setAttribute('src',generateSrc()); // add your logic in generateSrc
document.body.appendChild(elem);
To create dinamically your tag with timestamp, you can do it in two different ways:
By using DOM:
var e = document.createElement('script');
e.setAttribute('src',"myfile.js?tm="+(new Date()).getTime()); //(new Date()).getTime() Returns the number of milliseconds since midnight Jan 1, 1970
document.getElementsByTagName("body")[0].appendChild(e);
By using innerHTML:
document.getElementsByTagName("body")[0].innerHTML+= '<script src="myfile.js?tm='+(new Date()).getTime()+'"></script>';
Here's http://cjihrig.com/blog/passing-arguments-to-external-javascript-files/ a tutorial that explain how to pass and retrive arguments to an external script.

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.

Cloned row requesting same function [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
Call same function by a cloned list row
I am trying to make a simple calculation to work.
I have the following running:
http://jsfiddle.net/vSyK6/41/
Basically, the way it works now is this:
When you select an option on the drop down list it will display the content based on the option selected. Then when you select the same option again it will add, basically clone the same row.
Now, when the second option is selected "Option2" it will display an empty textbox. When you enter a number it will or should call the a function where we make a basic calculation. The function is already in the script.
However, when we have two empty textboxes it should call the same calculation function but calculate seperately and puts it in a different div. The div# where we display the amount is a called "amount"
Basically, it should work like this:
First Empty textbox -> 100 -> 100 * 22.38 = display result in div#1
Second Empty textbox -> 230 -> 230 * 22.38 = display in div#2
any idea on how to accomplish that ?
When cloning elements the id is cloned as well. It is best practice to create a new ID for the cloned elements, which will also help in accomplishing what you want. The same goes for the name attribute as well.
With a few modification to your code, http://jsfiddle.net/dNQVQ/3/, I was able to get what you were after. Let me first say that this might not be the ideal way to go, but it is a start. Like I said earlier the key is going to be setting unique ids for the cloned elements. What I did in this example was use a index as part of the list element id that is cloned with a matching index in an 'amount' div. This way when an input is updated the index is retrieved and then used to update the appropriate div. Additionally, I moved the function that did the calculation and updates to an anonymous function in the settimeout call. This makes it easy to use a reference to the updated input in the function call.
Joining the party quite late here :) Here is one vernon: http://jsfiddle.net/KVPwm/
ALso if its assignment bruv, put an assignment homework tag!
People around SO community are awesome folks so be truthful, guys will help man!
Use .on instead of live - recommendation. i.e. upgrade your JQ source if keen read this - What's wrong with the jQuery live method?
you have 2 document.ready functions also I chained few things for you.
Also think of using isNan check as well.
Rest you can read the code and play around a bit to make it more concise.
I have added 2 divs and using the id number to populate the stuff accordingly.
This should fit the cause :)
code
$("document").ready(function() {
/////////////////////////////////CALUCATIONS/////////////////////////////////
//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 0; //time in ms, 5 second for example
$('input[name=Input2], input[name=Input1]').live('keyup', function() {
var str = $(this).prop("id");
var pattern = /[0-9]+/g;
var matches = str.match(pattern);
amount = parseFloat($(this).val()) * 22.38;
typingTimer = setTimeout(doneTyping(matches), doneTypingInterval);
});
$('#Input2').keydown(function() {
clearTimeout(typingTimer);
});
function doneTyping(matches) {
$('#amount'+matches).text(amount.toFixed(2) + " lbs");
}
$("#List-Option1,#List-Option2").hide();
$('#category').change(function() {
var str = $('#category').val();
if (str == 'Option1') {
var option1 = $("#List-Option1:first").clone().show();
$('#box li:last').after(option1);
}
if (str == 'Option2') {
var option2 = $("#List-Option2:first").clone().show();
$('#box li:last').after(option2);
}
});
});​

Categories

Resources