Configuring Mediawiki UTCLiveClock Gadget - javascript

I am working with MediaWiki's UTCLiveClock.js and I am trying to configure it to put out a display time in PST/PDT. I thought I fixed the problem, however when midnight UTC hit (00:00:00) it changed my time output to 0-7:00:00. I need to to display properly so that when UTC 00:00:00 - 07:00:00 occurs, my time display doesn't look a mess. The gadget I am using through mediawiki can be found at https://www.mediawiki.org/wiki/MediaWiki:Gadget-UTCLiveClock.js
Yes, I'm a noob. I don't have any formal programming knowledge. I'm just trying to build a wiki for a game whose server exists in PST/PDT and running into this problem. Googling keyword searches for the last 3 hours has gotten me nowhere. Please help.
*/
/*global mw, $, UTCLiveClockConfig:true */
mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.notify']).then( function () {
var $target;
function showTime( $target ) {
var now = new Date();
var hh = now.getUTCHours();
var mm = now.getUTCMinutes();
var ss = now.getUTCSeconds();
var time = ( hh < 10 ? '0' + hh : hh ) + ':' + ( mm < 10 ? '0' + mm : mm ) + ':' + ( ss < 10 ? '0' + ss : ss );
$target.text( time );
var ms = now.getUTCMilliseconds();
setTimeout( function () {
showTime( $target );
}, 1100 - ms );
}
function liveClock() {
mw.util.addCSS( '#utcdate a { font-weight:bolder; font-size:120%; }' );
if ( !window.UTCLiveClockConfig ) {
UTCLiveClockConfig = {};
}
var portletId = UTCLiveClockConfig.portletId || 'p-personal';
var nextNode = UTCLiveClockConfig.nextNodeId ? document.getElementById( UTCLiveClockConfig.nextNodeId ) : undefined;
var node = mw.util.addPortletLink(
portletId,
mw.util.getUrl( null, { action: 'purge' } ),
'',
'utcdate',
null,
null,
nextNode
);
if ( !node ) {
return;
}
$( node ).on( 'click', function ( e ) {
new mw.Api().post( { action: 'purge', titles: mw.config.get( 'wgPageName' ) } ).then( function () {
location.reload();
}, function () {
mw.notify( 'Purge failed', { type: 'error' } );
} );
e.preventDefault();
} );
showTime( $( node ).find( 'a:first' ) );
}
$( liveClock );
} );
edit:
the way i originally fixed the problem is by putting a -7 in the hours section:
var hh = now.getUTCHours()-7;

It looks this is very simple Gadget limited to time in UTC. There are few options.
Find better script with support for time zones.
Write own script based on this one.
To write own script, there is critical part.
function get_PST_PDT_offset() {
/* You have to rewrite this function from time to time. */
var now = new Date();
var change = new Date(2016, 11, 5, 19, 0); /* 2016-11-06 2:00 PST */
if (now >= change) {
return -8;
} else {
return -7;
}
}
function showTime( $target ) {
var now = new Date();
var hh = now.getUTCHours();
var offset = get_PST_PDT_offset();
hh = (hh + offset + 24) % 24;
var mm = now.getUTCMinutes();
/* ... */

Related

Check if a HTML has loaded into a DIV

I want to be able to set up HTML pages and load them into a single home page. Each html file will be named as the date (eg 03052016.html for today) and then the correct html will be pulled in each day on the homepage.
However not all days will have a html file, in which case it should roll back to a previous day. I have successfully loaded the page, nice and easy but can't work out a way to identify that the page hasn't loaded and subtract one from the day. My current attempt is the following:
<body>
<div id="success"></div>
<script>
//section creates the html file name for today
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
var today = "05052016.html";
//do loop to subtract days until file is found
do{
var found = true; //variable records file presence
$( "#success" ).load( today, function( response, status, xhr ) {
if ( status == "error" ) {
var found = false;
if(parseInt(dd)>1){
dd = parseInt(dd)-1;
}else {
mm = parseInt(mm)-1;
dd = 30 //will deal with 31/30/28 day months later.
}
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = dd+mm+yyyy+'.html';
//
console.log( msg + xhr.status + " " + xhr.statusText );
}
});
}until(found == false )
</script>
I am new to web authoring so please be brutal if I am way off how to implement this. It seems so easy but the loop just won't work!
I am currently testing in FireFox, and using jquery-1.10.2.js
check de length of the content of the quuestioned div.
var div = $('div');
var dHtml = div.html();
var long = dHtml.length;
if(long > 0)
{
//do stuff
}
You need to understand that ajax (which is behind load) is asynchronous so you cannot test the found outside the success.
Try this:
function pad(num) {return String("0"+num).slice(-2)}
function getFilename(date)
var dd = pad(date.getDate());
var mm = pad(date.getMonth()+1); //January is 0!
var yyyy = date.getFullYear();
return ""+dd+mm+yyyy+".html";
}
var date = new Date(),
aDay = 10*24*60*60*1000,
giveUp = new Date(date.getTime()-(10*aDay)); // max 10 days back
function loadFile(date) {
$("#success").load( getFilename(date), function() {
if (status == "error") {
if (date>giveUp) {
date.setDate(date.getDate()-1)
loadFile(date);
}
}
});
}
$(function() {
loadFile(date);
});

Why this Js / jquery code uses %70 of CPU?

I'm using below code block to update my progress bar and some other things. But something is wrong. When this page loaded my cpu works like crazy. I stop it after N seconds so after 5 seconds everything must finish. Am I wrong?
var start = new Date();
var maxTime = 5000;
var maxTimeSec = maxTime / 1000; //convert ms to sec : 20000 / 1000 = 20 sec
var timeoutVal = Math.floor( maxTime / maxTimeSec ); //every 1 second
var counter = 0;
var tt = setInterval(function(){ animateUpdate() },1000);
//Call function
animateUpdate();
//Check is user logined
function isLogined(){
userId = $("#userInfo").attr("data-user") ;
userId = parseInt(userId);
var logined = false;
if(userId > 0){
logined = true;
}
return logined;
}
//send some data to somewhere
function sendStat(){
var lang = $("#langCode").attr("data-lang");
var url = $("#pageUrl").attr("data-pageUrl");
var title = $("#pageTitle").attr("data-pageTitle");
var user = $("#user").attr("data-user");
$.ajax({
type: "POST",
url: "/actions/setStats.php",
data: {
"url" : url,
"langCode" : lang,
"title" : title,
"user" : user
},
success: function(res){
console.log(res);
}
});
}
//My timer
function animateUpdate() {
var now = new Date();
var timeDiff = now.getTime() - start.getTime();
//var sec = maxTimeSec - Math.round( (timeDiff/maxTime) * maxTimeSec );
var perc = Math.round( (timeDiff/maxTime)*100);
//console.log(perc);
if(counter > maxTimeSec) {
clearInterval(tt);
var bottomDiv = $('#bottomDiv');
bottomDiv.show();
if( isLogined() ){
bottomDiv.text("Congratulations. You're lucky to read this article. We've updated your score.");
}else{
bottomDiv.text("Congratulations. You're lucky to read this article. If want to count your score you must login :)");
}
sendStat();
} else {
$('#timerProgress').css("width", perc + "%");
$('#timerCountdown').text(perc + "%");
//setTimeout(animateUpdate, timeoutVal);
counter++;
}
}
Maybe you should try using jQuery.animate() with callbacks?
Example:
http://codepen.io/anon/pen/JdMNem

Js onload and document.getElementById not working for me

Something in my code is not working. I am new to this. I think it is the onload maybe?
I am trying to convert a 24 clock to a 12 hour GMT server time clock and I have got as far as passing my new code to the CSS div I made.
All the CSS is fine and my coding works well with alert but not with onload and document.getElementById.
<script>
var currenttime = '<? print date("F d, Y H:i:s a", time())?>'
var serverdate=new Date(currenttime)
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = serverdate.getHours();
var hours = ((hours24 + 11) % 12) + 2;
formatted = [formatted, [addZero(hours), addZero(serverdate.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
document.getElementById("servertime").innerHTML=formatted
return formatted;
}
})();
window.onload=function(){
formatTime(new Date())
}
</script>
</head>
<body>
<h1><p><span id="servertime"></span></p></h1>
</body>
You could just write this, no need for javascript at all.
<h1><p><span id="servertime"><? print date("F d, Y h:i:s a", time())?></span></p></h1>
In case you are preparing a periodic update with your javascript (here it makes sense), I suggest using a simple jquery script for it:
$(document).ready(function() {
function update() {
$.ajax({
type: 'POST',
url: 'servertime.php',
timeout: 1000,
success: function(data) {
$("#servertime").html(data);
window.setTimeout(update, 1000);
},
});
}
update();
});

new Date return NaN or a wrong time starting from server date()

I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);

var change detect in html by jquery

I have a clock script and everything is fine, but I want to detect when the minutes change and add to this action some animation with jQuery, for example fadeToggle.
Can you tell me how can I detect the time change?
This is my script:
window.setInterval(function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
$.ajax({
success:function (clock) {
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
}
});
if (currentMinutes.length == 1) {
currentMinutes = "0" + currentMinutes;
}
}, 500);

Categories