Can someone help me to "convert" a external js script from a html page into a script in a .js file??
I have a countdown script, and a part of it is with these external link and i don't like it, can i put him into a js fie ??
<script type="text/javascript">
$(function() {
var endDate = "June 7, 2087 15:03:25";
$('.countdown.simple').countdown({ date: endDate });
$('.countdown.styled').countdown({
date: endDate,
render: function(data) {
$(this.el).html("<div>" + this.leadingZeros(data.years, 4) + " <span>years</span></div><div>" + this.leadingZeros(data.days, 3) + " <span>days</span></div><div>" + this.leadingZeros(data.hours, 2) + " <span>hrs</span></div><div>" + this.leadingZeros(data.min, 2) + " <span>min</span></div><div>" + this.leadingZeros(data.sec, 2) + " <span>sec</span></div>");
}
});
$('.countdown.callback').countdown({
date: +(new Date) + 10000,
render: function(data) {
$(this.el).text(this.leadingZeros(data.sec, 2) + " sec");
},
onEnd: function() {
$(this.el).addClass('ended');
}
}).on("click", function() {
$(this).removeClass('ended').data('countdown').update(+(new Date) + 10000).start();
});
// End time for diff purposes
var endTimeDiff = new Date().getTime() + 15000;
// This is server's time
var timeThere = new Date();
// This is client's time (delayed)
var timeHere = new Date(timeThere.getTime() - 5434);
// Get the difference between client time and server time
var diff_ms = timeHere.getTime() - timeThere.getTime();
// Get the rounded difference in seconds
var diff_s = diff_ms / 1000 | 0;
var notice = [];
notice.push('Server time: ' + timeThere.toDateString() + ' ' + timeThere.toTimeString());
notice.push('Your time: ' + timeHere.toDateString() + ' ' + timeHere.toTimeString());
notice.push('Time difference: ' + diff_s + ' seconds (' + diff_ms + ' milliseconds to be precise). Your time is a bit behind.');
$('.offset-notice').html(notice.join('<br />'));
$('.offset-server .countdown').countdown({
date: endTimeDiff,
offset: diff_s * 1000,
onEnd: function() {
$(this.el).addClass('ended');
}
});
$('.offset-client .countdown').countdown({
date: endTimeDiff,
onEnd: function() {
$(this.el).addClass('ended');
}
});
});
</script>
There is the code.
Thanks in advance :D
Yes, you can. Create a new file and call it countdown.js and place it in the same folder as your html file.
Then from inside your html page add
<script src="countdown.js"></script>
Related
I have a simple span and I want to show full date from Javascript inside this span. I'm not getting how to do it.
HTML (The date would be in place of the "..."):
<h3>Data Atual: </h3><span id="date" onload="newDate()">...</span>
Javascript:
function newDate() {
var dateBox = document.getElementById('date');
dateBox.innerHTML = '';
var date = new Date();
var newDate = date.getDay + ', ' + date.getDate + ' de ' + date.getMonth + ', ' + date.getFullYear + '.';
dateBox.innerHTML += newDate;
}
Thanks in advance
The load event doesn't fire on static HTML elements, only elements that load their data asynchronously from an external URL.
Put the call in the body's onload event.
<body onload="newDate()">
you can use this code to show the complete day in your span text:
document.getElementById("date").innerHTML = createNewDate();
function createNewDate() {
const date = new Date();
const newDate = date.getDay + ', ' + date.getDate + ' de ' + date.getMonth + ', ' + date.getFullYear + '.';
return newDate;
}
do not need to load it on start. Actually you are using get dates wrongly. This following code will solve it your problem. Put it before </body>
<script>
var date = new Date();
var newDate = date.getDay() + ', ' + date.getDate() + ' de ' + date.getMonth() + ', ' + date.getFullYear() + '.';
document.getElementById("date").innerHTML = newDate;
</script>
I want to format the time from 24 hours to 12 hours with AM/PM and display it in popover.
This is my code:
eventMouseover: function (event, jsEvent) {
var t1 = event.start;
var t2 = event.end;
$(this).popover({
html:true,
placement: 'left',
trigger: 'hover',
content: t1 + ' - ' + t2,
container: '#calendar'
}).popover('toggle');
}
I search for the answers here but it doesnt work in popover. So i decided to ask for it.
This is the code i used.
It works on here, but not in popover.
eventRender: function(event, element) {
var t1 = event.time;
var t2 = event.time2;
var tmpArr = t1.split(':'), time12;
if(+tmpArr[0] == 12) {
time12 = tmpArr[0] + ':' + tmpArr[1] + 'P';
} else {
if(+tmpArr[0] == 00) {
time12 = '12:' + tmpArr[1] + 'A';
} else {
if(+tmpArr[0] > 12) {
time12 = (+tmpArr[0]-12) + ':' + tmpArr[1] + 'P';
} else {
time12 = (+tmpArr[0]) + ':' + tmpArr[1] + 'A';
}
}
}
var tmpArrs = t2.split(':'), time13;
if(+tmpArrs[0] == 12) {
time13 = tmpArrs[0] + ':' + tmpArrs[1] + 'P';
} else {
if(+tmpArrs[0] == 00) {
time13 = '12:' + tmpArrs[1] + 'A';
} else {
if(+tmpArrs[0] > 12) {
time13 = (+tmpArrs[0]-12) + ':' + tmpArrs[1] + 'P';
} else {
time13 = (+tmpArrs[0]) + ':' + tmpArrs[1] + 'A';
}
}
}
element.find('.fc-content').append(t1 + "-" + t2 +);
}
Assuming you have moment.js included in your webpage (as FullCalendar needs it in any case) use the following code in place of declaring var t1 and var t2
var t1 = $.fullCalendar.moment(event.start).format("h:mm A")
var t2 = $.fullCalendar.moment(event.end ).format("h:mm A")
P.S. You don't need to work out the 12 hour format manually, moment.js does this for you
It's my first time using a countdown in javascript so I have researched a little about this topic and I found some interesting links: "how to countdown to a date" and "https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/", but my question is if I want to get data and time from the database, how can I do that? E.g.: I have a table Event with ID,Event,StartDate,StartTime and EndTime. How can I change from this: "var end = new Date('02/19/2012 10:1 AM');" from the first link or this: "Schedule the Clock Automatically" from the second to countdown time until event with the most recent time and date, and so on. Please keep in mind that I'm a total nooby so please bear with me. Sorry for any misspelling. Thank you!
Update:
This is the controller part: [HttpGet]
public JsonResult GetEvent(int Id)
{
BOL1.IMS2Entities db = new BOL1.IMS2Entities();
var ev = from e in db.tbl_Event
where e.ID == Id
select e;
//return Json(ev.FirstOrDefault(), JsonRequestBehavior.AllowGet);
return Json(Id, JsonRequestBehavior.AllowGet);
}
and this is the scripting part:
<script>
function GetEvent() {
debugger;
$.ajax({
type: "GET",
url: "Home/GetEvent",
data: { Id: ID },
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (result) {
debugger;
alert(result)
},
error: function (response) {
debugger;
alert('error');
}
});
}
var tbl_Event.StartDate = 'yyyy-MM-dd hh:hh:hh';
//var ServerDate_Time = '2017-02-17 10:45:00';
//console.log(CompareDateTime(ServerDate_Time));
console.log(CompareDateTime(tbl_Event.StartDate + tbl_Event.StartTime))
//function CompareDateTime (ServerDateTime){
function CompareDateTime (tbl_Event.StartDate + tbl_Event.StartTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
}
</script>
assuming your datetime you are getting int tbl_Event.StartDate + tbl_Event.StartTime = 2017-02-17 10:45:00
this will go for your..
var ServerDate_Time = '2017-02-17 10:45:00';
console.log(CompareDateTime(ServerDate_Time));
function CompareDateTime (ServerDateTime){
var dateString = new Date();
var currentTime = new Date(parseInt(dateString));
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if(ServerDateTime == date){
return true;
}else {
return false;
}
}
Hope this helps....
Edit after your Edit ....
Updated code...
For Controller --
[HttpGet]
public JsonResult GetEvent(int id)
{
using (IMS2Entities ObjEntities = new IMS2Entities())
{
var ev = from e in ObjEntities.tblEvents
where e.id == id
select e;
return Json(ev.ToList(), JsonRequestBehavior.AllowGet);
}
}
JavaScript code for this
<script>
$(function () {
GetEvent(); // this will call GetEvent function once your DOM is ready, you can call this function on button click or anywhere as per your need.
function GetEvent() {
$.ajax({
type: "GET",
url: "/Home/GetEvent",
data: { Id: '1' }, // '1' is id for my sql database record which is passing to controller to bring back record from server.
success: function (result) {
// result will be collection of list return form server, since you are using id criteria it will always have only 1 record unless you have id as foreign key or something not primary/unique.
// I'm using only first instance of result for demo purpose, you can modify this as per your need.
alert(CompareDateTime(result[0].StartDateTime.substr(6))); // this will alert your true or false, as per I guess this will always return false, as your current date time will never match sql datetime. Still for your requirement.
},
error: function (response) {
alert(response);
}
});
}
function CompareDateTime (ServerDateTimeFormat){
// Convert ServerDateTimeFormat for Comparision
var ServerdateString = ServerDateTimeFormat;
var ServerCurrentTime = new Date(parseInt(ServerdateString));
var Servermonth = ('0' + (ServerCurrentTime.getMonth() + 1)).slice(-2)
var Serverday = ('0' + (ServerCurrentTime.getDate())).slice(-2)
var Serveryear = ServerCurrentTime.getFullYear();
var Serverhours = ('0' + (ServerCurrentTime.getHours())).slice(-2)
var Servermin = ('0' + (ServerCurrentTime.getMinutes())).slice(-2)
var Serversec = ('0' + (ServerCurrentTime.getSeconds())).slice(-2)
var Serverdate = Serveryear + "-" + Servermonth + "-" + Serverday + " " + Serverhours + ":" + Servermin + ":" + Serversec;
// Current Date Time for Comparision
var currentTime = new Date();
var month = ('0' + (currentTime.getMonth() + 1)).slice(-2)
var day = ('0' + (currentTime.getDate())).slice(-2)
var year = currentTime.getFullYear();
var hours = ('0' + (currentTime.getHours())).slice(-2)
var min = ('0' + (currentTime.getMinutes())).slice(-2)
var sec = ('0' + (currentTime.getSeconds())).slice(-2)
var date = year + "-" + month + "-" + day + " " + hours + ":" + min + ":" + sec;
if (date == Serverdate) {
return true;
}else {
return false;
}
}
});
</script>
Please make sure you put reference for JQuery before ... tag.
This is fully working example.. :)
I'm using AngularJS to prefetch images in cache client and then I want to animate those prefetched images.
My code for the prefetching:
$scope.prefetch=function(limit) {
for (var i=0; i<limit; i++) {
var date = new Date($scope.dt);
if ($scope.fileFlag == false) {
if ($scope.viewmodel.timeResolution == 'yearly')
date = new Date(date.setFullYear(date.getFullYear() + i));
else if ($scope.viewmodel.timeResolution == 'monthly')
date = new Date(date.setMonth(date.getMonth() + i));
else if ($scope.viewmodel.timeResolution == 'daily') {
date = new Date(date.setDate(date.getDate() + i));
}
} else {
date = $scope.files[$scope.files.indexOf($scope.idSelectedVote) + i];
}
console.log( $http.get(site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + date + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap, {'cache': true}));
}
};
then i do something like this to play those images
$scope.play=function(limit) {
for (var i=0; i<limit; i++) {
$scope.map.src= site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
$scope.sleepFor(500);
}
};
$scope.sleepFor = function( sleepDuration ) {
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
My problem is when I call play(4) it displays only the first and the last images and not an animation. Any idea on how can I improve this code or a different approach so I can do this?
Your sleepFor is an idle loop: you spin and do nothing, but you prevent any other work from being done. This is not the way in Javascript to delay work for a set period of time, or schedule a function to be run at a later time. In Javascript we use window.setTimeout -- and in Angular we have the convenient $timeout service to provide that:
$scope.play = function(limit) {
for (var i=0; i < limit; i++) {
$scope.map.src = site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
var nextFrameMs = 500;
$timeout($scope.play, nextFrameMs);
}
};
In your example, wherever your $scope is provided to you -- assuming this is in a controller, you will have some line like module.controller($scope, ...) -- you will have to inject the $timeout service to be able to use it.
Additional resources:
Angular's documentation on $timeout
MDN documentation of window.setTimeout
You have to use intervals otherwise your code will block the execution of other code
Using Angular's built in $interval service is the solution:
var playInterval;
$scope.play = function(limit) {
var interval = 1000 / 20; //20 frames per second
var i = 0;
$interval.cancel(playInterval); //stop previous animations if any
if(i < limit) {
$scope.map.src = getSrc(i++);
var cache = $interval(function() {
if(i >= limit) {
return $interval.cancel(playInterval); //or you can replace with `i = 0;` to loop the animation
}
$scope.map.src = getSrc(i++);
}, interval);
}
};
function getSrc(i) {
return site_url + "mwf/" + $scope.viewmodel.dataSet + "/" + $scope.viewmodel.varName + "/" + $scope.viewmodel.region + "/" + parseInt(date)+i + "/map/?vMin=" + $scope.VMin + "&vMax=" + $scope.VMax + "&type=" + $scope.viewmodel.type + "&cmap=" + $scope.viewmodel.colorMap;
}
I'm relatively new to jQuery and JavaScript, and I think I understand what is causing my issue, but I'm not sure how to fix it.
I'm using SimpleWeather.JS , moment.js, and moment.js timezone to get the current time and weather for 4 cities. I have all the data I want on the page, but I want to move each city's time as the second paragraph in each city's div. Any ideas on how to get that working with my current code or is there a more efficient way of producing this result?
http://jsfiddle.net/ljd144/p6tpvz1r/
Here's my JS:
$(document).ready(function () {
$('.weather').each(function () {
var city = $(this).attr("city");
var woeid = $(this).attr("woeid");
var degrees = $(this).attr("degrees");
var continent = $(this).attr("continent");
$.simpleWeather({
zipcode: '',
woeid: woeid,
location: '',
unit: degrees,
success: function (weather) {
if (continent == 'America'){
html = '<p>' + weather.city + ', ' + weather.region + '</p>';
}
else {
html = '<p>' + weather.city + ', ' + weather.country + '</p>';
}
//html += '<p class="time" id="'+city+'></p>';
//html += '<p>' + weather.updated + '</p>';
html += '<p><i class="icon-' + weather.code + '"></i> ' + weather.temp + '°' + weather.units.temp + '<p>';
html += '<p>' + weather.currently + '<p>';
$('#weather_' + city).html(html);
},
error: function (error) {
$('#weather_' + city).html('<p>' + error + '</p>');
}
});
});
$(function () {
setInterval(function () {
$('.time').each(function () {
var city = $(this).attr("city");
var continent = $(this).attr("continent");
//$(this).text(city);
var utc = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(utc).toDate();
cityTime = moment(localTime).tz(continent + "/" + city).format('ddd MMM D YYYY, h:mm:ss a z');
$(this).text(city+ ': '+cityTime);
});
}, 1000);
});
$('.time').each(function () {
var city = $(this).attr("city");
//$('#weather_' + city).after(this);
});
});
You can use appendTo() method to append the time to the respective <div> having same city attribute using the attribute equals selector like:
$(this).text(city + ': ' + cityTime).appendTo("div[city='"+city+"']");
Updated fiddle
DEMO
Change:
$(this).text(city+ ': '+cityTime);
To:
var timeP = $('p.time','#weather_' + city);
timeP = timeP.length ? timeP : $('<p/>',{class:'time'}).appendTo( '#weather_' + city );
timeP.text(cityTime);