I am trying to make a simple age calculator. It simply adds the age on the side of the input. It calculates the age that is inside the input by datepicker.
The .split is not very clean but it is just to change date format.
I am guessing my problem is a problem of scope.
What I d like, is my plugin to update the age on change of the input. Here it is:
(function ($) {
$.fn.ageIt = function () {
var that = this;
var positonthat = $(that).position();
var sizethat = $(that).width();
//Add div for ages
var option = {
"position": " relative",
"top": "0",
"left": "300"
};
var templateage = "<div class='whatage" + $(this).attr('id') + "' style='display:inline-block;'>blablabla</div>";
$(that).after(templateage);
var leftposition = (parseInt(sizethat) + parseInt(positonthat.left) + parseInt(option.left));
var toposition = parseInt(positonthat.top) + parseInt(option.top);
$('.whatage' + $(this).attr("id")).css(
{
position: 'absolute',
top: toposition + "px",
left: leftposition + "px",
"z-index": 1000,
}
);
//uptadateage
function updateage(myobj) {
var formateddate = myobj.val().split(/\//);
formateddate = [formateddate[1], formateddate[0], formateddate[2]].join('/');
var birthdate = new Date(formateddate);
var age = calculateAge(birthdate);
$('.whatage' + $(myobj).attr("id")).text(age + " ans");
};
//updateage($(this));
$(this).on("change", updateage($(this)));
//
}
})(jQuery);
function calculateAge(birthday) {
var ageDifMs = Date.now() - birthday.getTime();
var ageDate = new Date(ageDifMs); // miliseconds from epoch
return Math.abs(ageDate.getUTCFullYear() - 1970);
}
$("#BirthDate").ageIt();
This line:
$(this).on("change", updateage($(this)));
means, "Set the handler for the 'change' event to the result of calling the function updateage() with the parameter $(this). That's a function call. Because you've already captured the value of this in the variable that, you can write updateage() such that it doesn't need a parameter:
function updateage() {
var formateddate = that.val().split(/\//);
formateddate = [formateddate[1], formateddate[0], formateddate[2]].join('/');
var birthdate = new Date(formateddate);
var age = calculateAge(birthdate);
$('.whatage' + $(that).attr("id")).text(age + " ans");
};
Then to set up the event handler:
$(this).on("change", updateage);
Note that in a jQuery add-on like you're building, the value of this will be the jQuery object upon which the method is called. You don't need to make a new jQuery object ($(this), $(that)). So it would work to just write:
this.on("change", updateage);
Related
I would like to create a simple if / else statement with JS. That would check if a div element has changed, before populating JSON data fields / variables that pull from dynamically changed HTML.
I do not want to use the DOMSubtreeModified. As it's depreciated..
Below is the started logic, I have. But it looks like I'll have to scrap the DOMSubtreeModified out for a method that is not depreciating.
The question / problem is: How to re-write not using the above depreciated technique, and how to nest my data array, where it will only pull / populate based on first checking my if (condition) Cheers for any pointers.
var element = document.querySelector('.username'); // username div wrapper
//if {
element.addEventListener('DOMSubtreeModified', function() { // detect if div element changes
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
console.log(time); // 7:01:21 PM
console.log(formattedDate); // 3/15/2016
}, false);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 3000);
// json object with captured data fields
var NewUserSession = [{
currentusername: $('.username').text(),
referrer: document.referrer,
loggedintime: $(formattedDate),
}];
//}
//
//else {
//
//
//}
You can use MutationObserver and watch for data-username changes
var element = document.querySelector('.username'); // username div wrapper
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName = 'data-username') {
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
snippet.log(time); // 7:01:21 PM
snippet.log(formattedDate); // 3/15/2016
}
});
});
var config = {
attributes: true,
attributeFilter: ['data-username']
};
// pass in the target node, as well as the observer options
observer.observe(element, config);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 1000);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="username"></div>
This is my javascript code, I checked it in Chrome and its not giving me an error
window.onload = function() {
var timeClock = function (){
setTimeout("timeClock()", 1000);
var timeObj = new Date();
var currTime = timeObj.getHours(); + " : " + timeObj.getMinutes(); + " : " + timeObj.getSeconds();
document.getElementById("#clock-container").innerHTML = "asd";
}
}
I am trying to update this div with the current system time
<div id="clock-container"></div>
You have multiple logic and other mistakes.
You are attempting to register the callback, but your setTimeout is in the callback itself. Move setTimeout("timeClock()", 1000); outside the callback.
Presumably you also want to replace setTimeout with setInterval to have the clock continuously update, and also avoid having to call setTimeout in the callback.
There's also no reason to use a string to call timeClock, so use setInterval(timeClock, 1000); instead and avoid the evil that is code evaluation.
document.getElementById("#clock-container") should be document.getElementById("clock-container").
Your currTime expression has several ; where they don't belong, fix those and you can use this variable instead of your string.
You can also call timeClock immediately after load, to avoid waiting for the first interval.
Working Example:
window.onload = function() {
var timeClock = function (){
var timeObj = new Date();
var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
document.getElementById("clock-container").innerHTML = currTime;
}
setInterval(timeClock, 1000);
timeClock();
}
<div id="clock-container"></div>
I am not sure what you're trying to do but The script should be
window.onload = function() {
var timeClock = function (){
var timeObj = new Date();
var currTime = timeObj.getHours() + " : " + timeObj.getMinutes() + " : " + timeObj.getSeconds();
document.getElementById("clock-container").innerHTML = currTime;
setTimeout(timeClock, 1000);
}
timeClock();
}
I tried create markers by JSON parse from C #.I have a small problem about datetime compare in javascript.
var nowDate= new Date();
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
var Time1= data2.LastRecordTime;
var image2;
var status;
if (new Date(Time1) < new Date(LastTenMin)) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1,
}
else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1,
}
else is not working ! There are truckOnline markers on google map.Where is my mistake ?
And LastRecordTime format like this in SQL : 04.12.2013 01:03:00
LastRecordTime=CONVERT(VARCHAR(10), [ReadTimeColumn], 104) + ' ' + CONVERT(VARCHAR(8), [ReadTimeColumn],108)
Mehmet,
Looks like you made a typo:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes(),- 10);
Should be (note the comma):
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes() - 10);
Also you were trying to create a new date object from a date object, this is incorrect:
new Date(LastTenMin)
And here is a more complete solution:
var nowDate= new Date();
var Time1 = new Date("04/12/2013 01:03:00");
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
// Should return true
console.log(Time1 < LastTenMin);
// Change the year to a point in the future
Time1 = new Date("04/12/2014 01:03:00");
// Shold return false
console.log(Time1 < LastTenMin);
// So your original conditional should look like this:
if (Time1 < LastTenMin) {
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1;
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1;
}
// And a more concise form:
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
Here is the solution without comments:
var nowDate= new Date();
var Time1 = new Date(data2.LastRecordTime);
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes() - 10);
var isOnline = !(Time1 < LastTenMin);
var image2 = isOnline ? '/Images/truckOnline.png' : '/Images/truckOffline.png';
var status = "Truck is " + (isOnline ? "Online" : "Offline") + "." + "\n" + "Last seen:" + " " + Time1
My whole solution is assuming that the string contained in data2.LastRecordTime is in the format: "MM.DD.YYYY HH:MM:SS".
This is going to sound like a cop out, but I would switch to MomentJS so you get the following code:
var Time1 = moment("04/12/2013 01:03:00");
var lastTenMin = moment().subtract({minutes: 10});
if(Time1.isBefore(lastTenMin)){
image2 = '/Images/truckOnline.png';
status = "Truck is online."+"\n"+"Last seen:"+" "+Time1.local();
} else {
image2 = '/Images/truckOffline.png';
status = "Truck is offline"+"\n"+"Last seen:"+" "+Time1.local();
}
Remember, JavaScript has random off-by-one issues for the date and month (one is zero-based, the other is one-based). The problem most likely is in this line:
var LastTenMin= new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(),nowDate.getHours(),nowDate.getMinutes()- 10);
If you switch to MomentJS, these kind of problems will disappear. I have lost many hours fighting these same issues, so I understand!
P.S. Try out the calendar() formatting feature... it may be a good fit in your UI.
To compare dates with time in Javascript we need to pass them in Date object as "yyyy/mm/dd HH:mm" format for e.g. like "2014/05/19 23:20" . Then you can just compare them with > or < less then symbol according to your business rule. Please see given below code for more understanding.
$(function () {
$("input#Submit").click(function () {
var startDateTime = $("input[name='StartDateTime']").val();
var endDateTime = $("input[name='EndDateTime']").val();
var splitStartDate = startDateTime.split(' ');
var splitEndDate = endDateTime.split(' ');
var startDateArray = splitStartDate[0].split('/');
var endDateArray = splitEndDate[0].split('/');
var startDateTime = new Date(startDateArray[2] + '/ ' + startDateArray[1] + '/' + startDateArray[0] + ' ' + splitStartDate[1]);
var endDateTime = new Date(endDateArray[2] + '/ ' + endDateArray[1] + '/' + endDateArray[0] + ' ' + splitEndDate[1]);
if (startDateTime > endDateTime) {
$("#Error").text('Start date should be less than end date.');
}
else {
$("#Error").text('Success');
}
});
});
You can also see a working demo here
I solved by SQL.
I set a new colum for difference minute between now and ReadTime.
DifferenceMinute=DATEDIFF(MINUTE,ReadTime,GETDATE())
if(DifferenceMinute>10)
{
bla bla
}
else
{
bla bla
}
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook + "," + "#"+$(this)
.parent()
.parent()
.parent()
.parent().attr("id") +
" #"+$(this).parent()
.parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
}
else
{
$(this).parent().parent().parent().children('.main-content').slideDown();
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
for(var i=0;i<a.length;i++){
var d = $(a[i++]);
var c = "#"+d.parent('.module').attr('id');
}
newCookie= c;
console.log(newCookie);
KillCookie('slideHide');
SetCookie('slideHide',d, 100);
}
});
These are my cookie functions:
function SetCookie(cookieName,cookieValue,nDays) {
var today = new Date();
var expire = new Date();
if (nDays==null || nDays==0) nDays=1;
expire.setTime(today.getTime() + 3600000*24*nDays);
document.cookie = cookieName+"="+escape(cookieValue)
+ ";expires="+expire.toGMTString(),';path = /';
}
function KillCookie(cookieName) {
SetCookie(cookieName,"", - 1);
}
function ReadCookie(cookieName) {
var theCookie=""+document.cookie;
var ind=theCookie.indexOf(cookieName+"=");
if (ind==-1 || cookieName=="") return "";
var ind1=theCookie.indexOf(";",ind);
if (ind1==-1) ind1=theCookie.length;
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}
Setting the cookie to make it slideUp and stay hidden works, but when I try to open it, it slidesDown, then I refresh the page it doesn't stay open like it should.
To sort of get the picture - http://jsfiddle.net/zRT9u/
If you need to know more please ask me I am willing to provide more!
I edited the javascript it almost works but I am not getting all the objects that I need
NEW EDIT- Tried the $.map() function but when I open one, and refresh all of them are now open?
else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[];
var a= $('.module').children('.main-content').filter(":hidden");
var c = $.map(a,function(n,i){
return $(n).parent().attr('id');
});
newCookie= c;
SetCookie('slideHide',newCookie, 100);
}
Fixed it by using $.map and .join()
var openClose = $('.openClose');
openClose.on('click', function() {
var cook = ReadCookie('slideHide'),
miniParent = $(this).parent().parent().parent().children('.main-content'),
miniDisp = miniParent.css('display');
if (miniDisp ==="block") {
KillCookie('slideHide');
$(this).parent().parent().parent().children('.main-content').slideUp();
var slide = cook+","+ "#"+$(this).parent().parent().parent().attr("id");
SetCookie('slideHide', slide, 100);
} else {
$(this).parent().parent().parent().children('.main-content').slideDown();
KillCookie('slideHide');
var newCookie=[],
a= $('.module').children('.main-content').filter(":hidden"),
c = $.map(a,function(n,i){
return "#"+$(n).parent().attr('id');
});
newCookie= c.join(',');
SetCookie('slideHide',newCookie, 100);
}
});
By creating a "global" array and then using the $.map function as well as adding "#"+ to the map function I was able to get the actual ID names. Then I set newCookie to c.join(',') and everything works perfectly after that!
I'm using the jqgrid, and to focus the popup to add, delete and edit, I need to use the parameter beforeShowForm that before this show window, shows the center of the screen. The problem is I have to always do the same code for these three functions.
The function is as follows:
{ // edit option
beforeShowForm: function(form) {
var dlgDiv = $("#editmod" + $(this)[0].id);
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth-dlgWidth )/2 ) + "px";
}
},
In order to reuse the same code, I would create a separate function to be always writing the same amount of code. I tried to create the following function:
Function:
function test(dlgDiv)
{
var parentDiv = dlgDiv.parent();
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth-dlgWidth )/2 ) + "px";
}
In Grid:
{ // edit option
beforeShowForm: function(form) {
var dlgDiv = $("#editmod" + $(this)[0].id);
test(dlgDiv);
}
},
But continued without giving. Says that the value dlgDiv is not defined. Does anyone know how to solve this?
The issue lies in the selector you use here:
var dlgDiv = $("#editmod" + $(this)[0].id);
Whatever element you're trying to get isn't being returned, because the selector can't find it. You should revise your selector to reflect the ID of the element you're attempting to find.
If you've done that and you still have an issue, the problem lies with your context and this doesn't mean what you think it means in the above line of code. You'll have to show us more code before I can elaborate on that, though.