Javascript Timers assistance - javascript

I am having some issues trying to use the console to modify the time remaining on one site.
I want to be able to set the Time remaining to zero to be able to proceed to the next page.
I believe that the issue is that there are multiple things that need to be set in order to proceed to the next page.
See code below, any help you can provide would be appreciated.
var pageLoaded = 0;
var timerStatus = 'pending';
var secondsRemaining = -1;
var secondsElapsed = -1;
var startTicks = 0;
var errorCount = 0;
var estimatedSecondsRemaining = -1;
var zeroTimeCounter = 0;
var intervalIdUpdateBothTimers;
var nonLinearGuid = null;
$(document).ready(function() {
setInterval('AutoSave()', 120000);
intervalIdUpdateBothTimers = setInterval('UpdateBothTimers()', 1000);
if (timerStatus == 'pending') {
var totaltimeclock = document.getElementById('TotalTimeClock');
if (totaltimeclock != null) {
document.getElementById('TotalTimeClock').innerHTML = '-- \: -- \: --';
}
var timeremainingclock = document.getElementById('TimeRemainingClock');
if (timeremainingclock != null) {
document.getElementById('TimeRemainingClock').innerHTML = '-- \: -- \: --';
}
StartTimer();
}
});
function loaded(i,f) {
if (document.getElementById && document.getElementById(i) != null)
{
f();
}
else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function SuspendTimer() {
UpdateBothTimers();
if (timerStatus == 'active') {
var data = "s=2&cp=" + this.location.pathname + "&nlg=" + GetNonLinearGuid();
timerStatus = 'suspended';
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
clearInterval(intervalIdUpdateBothTimers);
}
}
function AutoSave()
{
if (timerStatus == 'active')
{
SaveTime();
}
}
function SaveTime()
{
var data = '';
if (typeof window.IsScormPage === 'undefined')
{
data = "cp=" + this.location.pathname + "&sp=false";
}
else
{
data = "cp=" + this.location.pathname + "&sp=true";
}
data += "&nlg=" + GetNonLinearGuid();
$.ajax({
type: "POST",
url: "/Courses/ajax/CourseData.aspx",
data: data,
success: displayTime,
async: false
});
}
function StartTimer()
{
timerStatus = 'active';
SetNonLinearGuid();
SaveTime();
}
// Sets the nonLinearGuid with the one in the DOM
// the GUID was generated in the server side and
// passed it to the client side (DOM)
function SetNonLinearGuid()
{
var $nonLinearGuid = $("#nonLinearGuid");
if ($nonLinearGuid === undefined)
{
$nonLinearGuid = $("input[name=nonLinearGuid]");
}
if ($nonLinearGuid.length)
{
nonLinearGuid = $nonLinearGuid.val() || null;
window.nonLinearGuid = window.nonLinearGuid || nonLinearGuid;
}
}
function GetNonLinearGuid() {
var nlg = (window.NonLinearGuid || nonLinearGuid),
admin = getQueryStringByName("admin", parent.window.location.href) || "";
if (admin.toLowerCase() == "d3v") {
printNonLinearGuid(nlg);
}
return nlg;
}
function getQueryStringByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
function displayTime(result)
{
if (result.isOk == false)
{
alert(result.message);
}
else
{
var d = new Date();
startTicks = d.getTime();
secondsRemaining = parseInt($(result).find("SecondsRemaining").text());
secondsElapsed = parseInt($(result).find("SecondsElapsed").text());
redirectUrl = $(result).find("RedirectUrl").text();
var suspendTimer = $(result).find("SuspendTimer").text();
var dataNonLinearGuid = "?nlg=" + GetNonLinearGuid();
if (redirectUrl != "") {
location.href = redirectUrl;
}
isError = $(result).find("Error").text();
if (isError == "true")
{
errorCount++;
if (errorCount > 3)
{
logout();
}
}
isOverworked = $(result).find("IsOverworked").text();
if (isOverworked == "true")
{
location.href = "/Courses/MyAccountNonLinear.aspx" + dataNonLinearGuid;
}
if (suspendTimer.length > 0) {
if ($.trim(suspendTimer).toLowerCase() == "true") {
SuspendTimer();
}
}
}
}
function logout()
{
window.top.location.href = "/Courses/loggedout.aspx";
}
function UpdateBothTimers() {
if (timerStatus != 'active') return;
if (secondsElapsed >= 0)
{
UpdateElapsedTimer();
//secondsElapsed++;
}
if (secondsRemaining >= 0) {
UpdateRemainingTimer();
}
if (estimatedSecondsRemaining <= 0 && zeroTimeCounter == 0) {
zeroTimeCounter++;
SaveTime();
}
}
var lang;
function qt(m,lng) {
$('#timeRemaining').css('display', 'none');
setTimeout("$('#EOMQuiz').submit();", m * 1000);
lang = lng;
setTimeout('updateQ('+ m +')', 1000);
}
function updateQ(m) {
--m;
var text;
if (lang == 'es') {
text = 'Entregar - ' + m + ' segundos restantes para completar la prueba';
}
else {
text = 'Submit - ' + m + ' seconds remaining to complete the quiz';
}
if (m > 0) {
setTimeout('updateQ('+m+')', 990);
}
else
{
$('#eomsubmitDiv').css('background-color', '#FF0000');
text ='Submitting... Please Wait.';
}
if (m <= 10 && m > 0)
{
if (m % 2 == 0)
{
$('#eomsubmitDiv').css('background-color', '#FFFF00');
}
else
{
$('#eomsubmitDiv').css('background-color', '#FFFFAA');
}
}
$('#eomsubmit').attr('value', text);
}
function UpdateElapsedTimer()
{
var s = secondsElapsed + (GetTickDiff()/1000);
UpdateTimer('TotalTimeClock', s, 'UP');
}
function GetTickDiff()
{
var d = new Date();
var tickDiff = d.getTime() - startTicks;
return tickDiff;
}
function UpdateRemainingTimer()
{
var s = secondsRemaining - (GetTickDiff()/1000);
estimatedSecondsRemaining = s;
if (s < 0) s = 0;
UpdateTimer('TimeRemainingClock', s, 'DOWN');
}
function UpdateTimer(ClockID,ElapsedSeconds,ClockDirection){
//check to see if we can run this code yet
if(document.getElementById && document.getElementById(ClockID) != null){
//declare vars
var _Seconds = 0;
var _Minutes = 0;
var _Hours = 0;
//Format Seconds
_Seconds = Math.floor(ElapsedSeconds % 60);
if(_Seconds <= 9) {
_Seconds = "0"+_Seconds;
}
//Format minutes
_Minutes = Math.floor(ElapsedSeconds/60 % 60);
if(_Minutes <= 9) {
_Minutes = "0"+_Minutes;
}
//Format hours
_Hours = Math.floor(ElapsedSeconds/3600 % 60);
if(_Hours <= 9){
_Hours = "0"+_Hours;
}
document.getElementById(ClockID).innerHTML = _Hours + ":" + _Minutes + ":" + _Seconds;
if (timerStatus != 'active')
{
setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
return;
}
if(ElapsedSeconds > 0 || ClockDirection == "UP"){
if(ClockDirection == "UP")
{
ElapsedSeconds = ElapsedSeconds + 1;
}
else
{
ElapsedSeconds = ElapsedSeconds - 1;
}
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',1000);
}
else{
//Timer has hit zero. Lets make sure the next buttons are visible.
$('#next_top').show();
$('#next_bot').show();
}
}
else if(!pageLoaded) //call function again in 100ms
{
//setTimeout('UpdateTimer(\''+ClockID+'\','+ElapsedSeconds+',\''+ClockDirection+'\')',100);
}
}
function DisplayNextButtons(){
$('#next_top').show();
$('#next_bot').show();
}
function hideNextButtons(){
$('#next_top').hide();
$('#next_bot').hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I happened to stumble upon the same code. If you were on the same site as me,
I have a potential fix.
Instead of editing the time remaining I setup a script that will click next when the time has expired. I was too lazy to check whether they are checking timestamps server side. Also the server logs will look more similar to a regular user.
Instructions:
Download the following extension for Chrome
https://chrome.google.com/webstore/detail/custom-javascript-for-web/poakhlngfciodnhlhhgnaaelnpjljija?hl=en
Navigate to the site
click the CJS chrome extension button
check "enable cjs for this host"
paste the following JS snippet into the JS box
var t=setInterval(try_hit_next,1000);
function try_hit_next(){
if (estimatedSecondsRemaining <= 0)
window.location = $('#next_top').parent()[0]['href'];
}
click save

1) No needs to assign "setInterval" to a variable t
2) Has somebody tried to make fully automated script for this resource, i mean "driving defensive course" cause it pushes popups with personal questions randomly and besides shows pages with a сourse-related questions (constantly the same), so hope it's gonna be very useful "tool" )

Unfortunately the timers are actually being kept server-side. You can watch a POST to CourseData.aspx and it will return with new values for SecondsRemaining and SecondsElapsed. These new values are used to set the client-side timers. You can change the client side variables all you want but when you move to the next page, another call to CourseData.aspx is done to fetch the server time. So the server's timers rule this entire process.
I believe the only reason you see any JS timers is to provide a (now hidden) simple "time remaining" clock for the user.
However I am willing to bet that there's a way to POST a new time or SecondsRemaining to the CourseData.aspx page, I just don't know what set of post data variables might be needed to do so.

Related

Have to call alert for rest JS to run on Iphone (safari)

I'm having trouble with JS code not executing on iPhone if I don't call alert before if statement. This is my code:
submitHandler = (e) => {
e.preventDefault();
var dataFromForm = $("#send").serialize();
alert(); // Without this the code below wont execute on iphne
if (window.localStorage) {
if (localStorage.getItem("timeout")) {
const timePrev = localStorage.getItem("timeout");
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) {
var available = true;
} else {
var available = false;
document.getElementById("message").innerHTML =
'<span class="fail"> Spam protection</span>';
}
} else {
var available = true;
}
} else {
var available = true;
}
if (available) {
$.post("mail.php", dataFromForm, function (data) {
document.getElementById("message").innerHTML = "";
console.log(data);
data = JSON.parse(data);
console.log(data);
if (data.statusBool === true) {
document.getElementById("message").innerHTML =
'<span class="success">' + data.status + "</span>";
document.getElementById("name").value = "";
document.getElementById("email").value = "";
document.getElementById("msg").value = "";
var timenow = Math.round(new Date().getTime() / 1000);
localStorage.setItem("timeout", timenow);
} else {
document.getElementById("message").innerHTML =
'<span class="fail">' + data.status + "</span>";
}
});
}
setTimeout(function () {
document.getElementById("message").innerHTML = "";
}, 3000);
};
code below alert doesn't execute if I don't put alert before that statement.
Does anyone know how to solve this, or have an idea of what could I use instead of alert, so it's not visible for the user?
Answer by #Chris G
jsfiddle.net/rqht1kzo
localStorage.setItem('timeout', new Date().getTime() / 1000 - 400);
var available = false;
const timePrev = window.localStorage && window.localStorage.getItem('timeout');
if (timePrev) {
const timeNow = Math.round(new Date().getTime() / 1000);
if (timeNow - timePrev >= 300) available = true;
}
if (available) {
console.log("it's available")
} else {
document.getElementById('message').innerHTML = '<span class="fail"> fail message</span>';
}

How to redirect the countdown of the jCounter plugin after the end only once, without infinite loop?

I'm using the Jcounter plugin http://devingredients.com/jcounter/ on a project, it's perfect for what I need, except for a problem I'm facing. I need it when I finish the countdown, it updates the same page only once, without giving infinite loop. How can I do this?
The callback function seems to give this possibilide, would I need some control? I have little experience in jquery.
<!DOCTYPE html>
<html>
<head>
<title>jCounter - jQuery plugin - devingredients.com</title>
<meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/jquery.jCounter-iosl.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.jCounter-0.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//first counter
$(".countdown1").jCounter({
animation: "slide",
date: "2017/10/13 19:53:20",
format: "dd:hh:mm:ss",
twoDigits: 'on',
callback: function() {
window.location.href = "index.php?block=Yes"
}
});
});
</script>
<div class="iosl-theme-wrapper countdown1">
<div class="iosl-theme">
<ul>
<li><p><span><em><b class="days">00</b><i class="daysSlider"><u>00</u><u>00</u></i></em></span></p></li>
<li><p><span><em><b class="hours">00</b><i class="hoursSlider"><u>00</u><u>00</u></i></em></span></p></li>
<li><p><span><em><b class="minutes">00</b><i class="minutesSlider"><u>00</u><u>00</u></i></em></span></p></li>
<li><p><span><em><b class="seconds">00</b><i class="secondsSlider"><u>00</u><u>00</u></i></em></span></p></li>
</ul>
<div class="jC-clear"></div>
<p class="jCtext">
<span><em class="textSeconds">SEGUNDOS</em></span>
<span><em class="textMinutes">MINUTOS</em></span>
<span><em class="textHours">HORAS</em></span>
<span><em class="textDays">DIAS</em></span>
</p>
<div class="jC-clear"></div>
</div>
</div>
**jquery.jCounter-0.1.4.js**
/**********************************
* jCounter Script v0.1.4 (beta)
* Author: Catalin Berta
* Official page and documentation: http://devingredients.com/jcounter
* Licensed under the MIT license
**********************************/
;(function($,document,window,undefined) {
//once upon a time...
$.fn.jCounter = function(options,callback) {
var jCounterDirection = 'down'; // points out whether it should count down or up | handled via customRange setting
var customRangeDownCount; //if true, it will tell countdown_proc() it's a down count and not an up count
var days,hours,minutes,seconds;
var endCounter = false; //stops jCounter if true
var eventDate; //time target (holds a number of seconds)
var pausedTime; //stores the time (in seconds) when pausing
var thisEl = this; //custom 'this' selector
var thisLength = this.length; //number of multiple elements per selector
var pluralLabels = new Array('DAYS','HOURS','MINUTES','SECONDS'); //plural labels - used for localization
var singularLabels = new Array('DAY','HOUR','MINUTE','SECOND'); //singular labels - used for localization
this.options = options; //stores jCounter's options parameter to verify against specified methods
this.version = '0.1.4';
//default settings
var settings = {
animation: null,
callback: null,
customDuration: null,
customRange: null,
date: null,
debugLog: false,
serverDateSource: 'dateandtime.php', //path to dateandtime.php file (i.e. http://my-domain.com/dateandtime.php)
format: 'dd:hh:mm:ss',
timezone: 'Europe/London',
twoDigits: 'on'
};
//merge the settings with the options values
if (typeof options === 'object') {
$.extend(settings,options);
thisEl.data("userOptions", settings); //push the settings to applied elements (they're used by methods)
}
if(thisEl.data('userOptions').debugLog == true && window['console'] !== undefined ) {
var consoleLog = true; //shows debug messages via console.log() if true
}
//METHODS
var jC_methods = {
//initialize
init : function() {
thisEl.each(function(i,el) {
initCounter(el);
});
},
//pause method: $.jCounter('pause')
pause : function() {
if(consoleLog) { console.log("(jC) Activity: Counter paused."); }
endCounter = true;
return thisEl.each(function(i,el) {
clearInterval($(el).data("jC_interval"));
});
},
//stop method: $.jCounter('stop')
stop : function() {
if(consoleLog) { console.log("(jC) Activity: Counter stopped."); }
endCounter = true;
return thisEl.each(function(i,el) {
clearInterval($(el).data("jC_interval"));
$(el).removeData("jC_pausedTime");
resetHTMLCounter(el);
});
},
//reset method: $.jCounter('reset')
reset : function() {
if(consoleLog) { console.log("(jC) Activity: Counter reset."); }
return thisEl.each(function(i,el) {
clearInterval($(el).data("jC_interval"));
resetHTMLCounter(el);
initCounter(el);
});
},
//start method: $.jCounter('start')
start : function() {
if(consoleLog) { console.log("(jC) Activity: Counter started."); }
return thisEl.each(function(i,el) {
pausedTime = $(el).data("jC_pausedTime");
endCounter = false;
clearInterval($(el).data("jC_interval"));
initCounter(el);
});
}
}
//checks whether customDuration is used
if(thisEl.data("userOptions").customDuration) {
if(!isNaN(thisEl.data("userOptions").customDuration)) {
var customDuration = true;
} else {
var customDuration = false;
if(consoleLog) { console.log("(jC) Error: The customDuration value is not a number! NOTE: 'customDuration' accepts a number of seconds."); }
}
}
//checks whether customRange is used
if(thisEl.data("userOptions").customRange) {
var customRangeValues = thisEl.data("userOptions").customRange.split(":");
var rangeVal0 = parseInt(customRangeValues[0]);
var rangeVal1 = parseInt(customRangeValues[1]);
if(!isNaN(rangeVal0) && !isNaN(rangeVal1)) {
var customRange = true;
if(rangeVal0 > rangeVal1) {
var customRangeDownCount = true;
} else {
var customRangeDownCount = false;
jCounterDirection = 'up';
}
} else {
var customRange = false;
if(consoleLog) { console.log("(jC) Error: The customRange value is not a valid range! Example: customRange: '0:30' or '30:0'"); }
}
}
//checks whether animation is set to slide
if(thisEl.data("userOptions").animation == 'slide') {
thisEl.data("jCanimation","slide");
}
//FUNCTIONS
//jCounter initializer
function initCounter(el) {
if(customDuration) {
if (pausedTime) {
if (!isNaN(pausedTime)) {
eventDate = Math.round(pausedTime);
}
} else {
eventDate = Math.round($(el).data("userOptions").customDuration);
}
currentTime = 0;
countdown_proc(currentTime,el);
$(el).data("jC_interval", setInterval(function(){
if(endCounter == false) {
currentTime = parseInt(currentTime) + 1;
countdown_proc(currentTime,el)
}
},1000));
} else if(customRange) {
eventDate = Math.round(customRangeValues[1]);
if (pausedTime) {
if (!isNaN(pausedTime)) {
var currentTime = eventDate - pausedTime;
}
} else {
var currentTime = Math.round(customRangeValues[0]);
}
countdown_proc(currentTime,el);
$(el).data("jC_interval", setInterval(function(){
if(endCounter == false) {
var ifRangeDownCount = (customRangeDownCount) ? currentTime = parseInt(currentTime) - 1 : currentTime = parseInt(currentTime) + 1;
countdown_proc(currentTime,el);
}
},1000));
} else {
eventDate = Date.parse($(el).data("userOptions").date) / 1000;
dateSource = thisEl.data("userOptions").serverDateSource + '?timezone=' + thisEl.data("userOptions").timezone + '&callback=?';
$.ajax({
url: dateSource,
dataType : 'json',
data : {},
success : function(data, textStatus){
var currentDate = Date.parse(data.currentDate) / 1000;
startCounter(currentDate,el);
},
error : function(){
if(consoleLog) { console.log("(jC) Error: Couldn't find dateandtime.php from serverDateSource: " + thisEl.data('userOptions').serverDateSource + "\n(jC) - Make sure the path is correct! \n(jC) - Now using the client-side time (not recommended).") }
var currentDate = Math.floor($.now() / 1000);
startCounter(currentDate,el);
}
});
}
}
function startCounter(currentDate,el) {
countdown_proc(currentDate,el);
if (eventDate > currentDate) {
$(el).data("jC_interval", setInterval(function(){
if(endCounter == false) {
currentDate = parseInt(currentDate) + 1;
countdown_proc(currentDate,el)
}
},1000));
} else {
resetHTMLCounter(el)
}
}
//jCslider - adds the slide effect layer
//Note: this requires a jCounter slide-ready theme! (i.e. iOS dark or iOS light)
function jCslider(el,unitClass,timeUnit,eventDate,duration) {
$(el).find(unitClass + " u").each(function(i,el) {
var twoDigits = (thisEl.data("userOptions").twoDigits == 'on') ? '0' : '';
var newIndex = (jCounterDirection == 'up') ? newIndex = -i : newIndex = i;
currNo = parseInt(timeUnit,10) + (newIndex);
if (String(parseInt(timeUnit,10)).length >= 2) {
$(el).text(parseInt(timeUnit,10) + (newIndex))
} else if(String(parseInt(timeUnit,10)).length == 1 && currNo == 10) {
$(el).text(parseInt(timeUnit,10) + (newIndex))
} else {
$(el).text(twoDigits + (parseInt(timeUnit,10) + (newIndex)));
}
})
$(el).find(unitClass).animate({
top: '0.15em'
},200, function() {
$(el).find(unitClass + " u:eq(1)").remove();
$(el).find(unitClass).prepend('<u></u>');
$(el).find(unitClass).css({'top':'-1.24em'})
});
}
//resets jCounter's HTML values to 0 or 00, based on the twoDigits setting
function resetHTMLCounter(el) {
if(thisEl.data("userOptions").twoDigits == 'on') {
$(el).find(".days,.hours,.minutes,.seconds").text('00');
} else if(thisEl.data("userOptions").twoDigits == 'off') {
$(el).find(".days,.hours,.minutes,.seconds").text('0');
}
if(thisEl.data("jCanimation") == 'slide') {
$(el).find(".daysSlider u,.hoursSlider u,.minutesSlider u,.secondsSlider u").text('00');
}
}
//main jCounter processor
function countdown_proc(duration,el) {
//check if the counter needs to count down or up
if(customRangeDownCount) {
if(eventDate >= duration) {
clearInterval($(el).data("jC_interval"));
if(thisEl.data("userOptions").callback) {
thisEl.data("userOptions").callback.call(this);
}
}
} else {
if(eventDate <= duration) {
clearInterval($(el).data("jC_interval"));
if(thisEl.data("userOptions").callback) {
thisEl.data("userOptions").callback.call(this);
}
}
}
//if customRange is used, update the seconds variable
var seconds = (customRange) ? duration : eventDate - duration;
var thisInstanceFormat = thisEl.data("userOptions").format;
//calculate seconds into days,hours,minutes,seconds
//if dd (days) is specified in the format setting (i.e. format: 'dd:hh:mm:ss')
if(thisInstanceFormat.indexOf('dd') != -1) {
var days = Math.floor(seconds / (60 * 60 * 24)); //calculate the number of days
seconds -= days * 60 * 60 * 24; //update the seconds variable with no. of days removed
}
//if hh (hours) is specified
if(thisInstanceFormat.indexOf('hh') != -1) {
var hours = Math.floor(seconds / (60 * 60));
seconds -= hours * 60 * 60; //update the seconds variable with no. of hours removed
}
//if mm (minutes) is specified
if(thisInstanceFormat.indexOf('mm') != -1) {
var minutes = Math.floor(seconds / 60);
seconds -= minutes * 60; //update the seconds variable with no. of minutes removed
}
//if ss (seconds) is specified
if(thisInstanceFormat.indexOf('ss') == -1) {
seconds -= seconds; //if ss is unspecified in format, update the seconds variable to 0;
}
//conditional Ss
//updates the plural and singular labels accordingly
if (days == 1) { $(el).find(".textDays").text(singularLabels[0]); } else { $(el).find(".textDays").text(pluralLabels[0]); }
if (hours == 1) { $(el).find(".textHours").text(singularLabels[1]); } else { $(el).find(".textHours").text(pluralLabels[1]); }
if (minutes == 1) { $(el).find(".textMinutes").text(singularLabels[2]); } else { $(el).find(".textMinutes").text(pluralLabels[2]); }
if (seconds == 1) { $(el).find(".textSeconds").text(singularLabels[3]); } else { $(el).find(".textSeconds").text(pluralLabels[3]); }
//twoDigits ON setting
//if the twoDigits setting is set to ON, jCounter will always diplay a minimum number of 2 digits
if(thisEl.data("userOptions").twoDigits == 'on') {
days = (String(days).length >= 2) ? days : "0" + days;
hours = (String(hours).length >= 2) ? hours : "0" + hours;
minutes = (String(minutes).length >= 2) ? minutes : "0" + minutes;
seconds = (String(seconds).length >= 2) ? seconds : "0" + seconds;
}
//updates the jCounter's html values
if(!isNaN(eventDate)) {
$(el).find(".days").text(days);
$(el).find(".hours").text(hours);
$(el).find(".minutes").text(minutes);
$(el).find(".seconds").text(seconds);
if(thisEl.data("jCanimation") == 'slide') {
$(el).find(".daysSlider u:eq(1)").text(days);
$(el).find(".hoursSlider u:eq(1)").text(hours);
$(el).find(".minutesSlider u:eq(1)").text(minutes);
$(el).find(".secondsSlider u:eq(1)").text(seconds);
jCslider(el,'.secondsSlider',seconds,eventDate,duration);
if(parseInt(seconds,10) == 59) {
jCslider(el,'.minutesSlider',minutes,eventDate,duration)
if(parseInt(minutes,10) == 59) {
jCslider(el,'.hoursSlider',hours,eventDate,duration)
if(parseInt(hours,10) == 23) {
jCslider(el,'.daysSlider',days,eventDate,duration)
}
}
}
}
} else {
if(consoleLog) { console.log("(jC) Error: Invalid date! Here's an example: 01 January 1970 12:00:00"); }
clearInterval($(el).data("jC_interval"));
}
//stores the remaining time when pausing jCounter
$(el).data("jC_pausedTime", eventDate-duration);
}
//method calling logic
if ( jC_methods[this.options] ) {
return jC_methods[ this.options ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof this.options === 'object' || ! this.options ) {
return jC_methods.init.apply( this, arguments );
} else {
console.log('(jC) Error: Method >>> ' + this.options + ' <<< does not exist.' );
}
}
//the end;
}) (jQuery,document,window);

Coundown cokie set up

I cant figuret how set cookie for my countdownt timeer, that if i refresh page it vill not disapear but vill counting.
i be glad if eny can help. i use jquery 2.1.4 and this java countdown script, but when i refresh page all my coundown timers are lost!
/**
* Created by op on 18.07.2015.
*/
function leadZero (n)
{
n = parseInt(n);
return (n < 10 ? '0' : '') + n;
}
function startTimer(timer_id) {
var timer = $(timer_id);
var time = timer.html();
var arr = time.split(":");
var h = arr[0];
h = h.split(" / ");
h = h[1];
var m = arr[1];
var s = arr[2];
if (s == 0)
{
if (m == 0)
{
if (h == 0)
{
timer.html('')
return;
}
h--;
m = 60;
}
m--;
s = 59;
}
else
{
s--;
}
timer.html(' / '+leadZero(h)+":"+leadZero(m)+":"+leadZero(s));
setTimeout(function(){startTimer(timer_id)}, 1000);
}
function timer (name, time)
{
var timer_name = name;
var timer = $(timer_name);
var time_left = time;
timer.html(' / '+ time);
startTimer(timer_name);
}
$(document).ready(function(){
$('.fid').click(function (e)
{
var timer_name = '.timer_'+$(this).data('fid');
var timer = $(timer_name);
if (timer.html() == '')
{
var time_left = timer.data('timer');
var hours = leadZero(Math.floor(time_left / 60));
var minutes = leadZero(time_left % 60);
var seconds = '00';
timer.html(' / '+hours+':'+minutes+':'+seconds);
startTimer(timer_name);
}
});
$.each($('.tab'), function () {
$(this).click(function () {
$.each($('.tab'), function() {
$(this).removeClass('active');
});
$(this).addClass('active');
$('.list').hide();
$('#content-'+$(this).attr('id')).show();
});
});
if (window.location.hash != '')
{
var tab = window.location.hash.split('-');
tab = tab[0];
$(tab).click();
}
console.log(window.location.hash)
});
It would help if you actually set a cookie.
Setting the cookie would go like:
document.cookie="timer=" + time;
And then call it at the beginning of your code
var time = getCookie("timer");
The getCookie() function is outlined in that link, as well as a base knowledge about them.

How to override event.stopPropagation(),preventDefault().stopImmediatePropagation()

I am trying to modify Jira Tempo plugin's plan work form. So in the tempo time sheet page
I have a button who has 2 actions bind-ed, one is a click action and one is a focus out.
the click action opens a popup. and the focus out verifies the form in the popup. I need the clik action to be executed first and then the focus out.
The problem is when the popup opens there is a call to all of the three functions.
event.stopPropagation().preventDefault().stopImmediatePropagation(); so the focus out does not fire in chrome.
In IE10 and Firefox works great.
Can i override jQuery basic function ofevent.stopPropagation().preventDefault().stopImmediatePropagation() to do not apply for that button?
all three, maybe?
I tried this:
(function () {
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
stopPropagation: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if (e && e.stopPropagation) {
e.stopPropagation();
}
}
},
preventDefault: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if (e && e.preventDefault) {
e.preventDefault();
}
}
},
stopImmediatePropagation: function () {
if (jQuery('#tempo-plan-button').hasClass(this.currentTarget.className)) {
} else {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if (e && e.stopImmediatePropagation) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
}
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
})();
UPDATE:
I don't have control on what the click function does, but i have control on the focus out, I have made some test and i looks like Chrome does not see the focus out event, because the element is hidden before the focus out occurs ( it is a popup button).
I managed to call my functions with mouse out event but this does not work on IE so I have to bind separate event listener for IE and Chrome,Firefox,Safari.
Can you help with some browser detection examples.
UPDATE 2:
My problem solved with a different listener to the popup element. ex:
jQuery(document).ready(function ($) {
var currentUser = null;
var selected = null;
var opened = null;
var formOpened = null;
var activityField = null;
var activitySelected = null;
var popupBody = null;
var formOpened = null;
var periodCheckbox = null;
var dateField = null;
var endDateField = null;
var plannedHours = null;
var periodselected = null;
var days = 1;
var startdate = 0;
var enddate = 0;
var planButton = $('#tempo-plan-button');
//this is the default LM-Holiday activity ID set this
value to corespond with the value on jira tempo form.
var holidayid = "10100";
var holidaysLeft = 21; /*
$('#tempo-plan-button').click(function () {
alert("click event");
});
$('#tempo-plan-button').focusin(function () {
alert("focus event");
});
$('#tempo-plan-button').hover(function () {
alert("hover event");
});
$('#tempo-plan-button').mouseleave(function () {
alert("mouse leave event");
});
$('#tempo-plan-button').mouseout(function () {
alert("mouse out event");
}); */
$('body').one('focus', 'div[class="aui-popup aui-dialog"]', function (event) {
$('div[class="aui-popup aui-dialog"]').each(function () {
popupBody = $(this).find(".dialog-components");
if ($(this).find(".dialog-title").hasClass("tempo-add-button") === false) {
i = 0;
j = 0;
$(popupBody).find(".dialog-page-menu li").each(function () {
if ($(this).attr("class") === "page-menu-item selected") {
button = $(this).find('.item-button');
if ((button).text() === "Internal") {
selected = i;
}
}
i++;
});
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === null) {
i = 0;
j = 0;
$(popupBody).find(".dialog-page-menu li").click(function () {
$(popupBody).find(".dialog-page-menu li").each(function () {
if ($(this).attr("class") === "page-menu-item selected") {
button = $(this).find('.item-button');
if ((button).text() === "Internal") {
selected = i;
}
}
i++;
});
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === opened) {
activityField = $(formOpened).find('.tempo-activity-picker.select');
periodCheckbox = $(formOpened).find('.showperiod.tempo-show-period');
dateField = $(formOpened).find(' input[name="date"]');
endDateField = $(formOpened).find('input[name="enddate"]');
plannedHours = $(formOpened).find('input[name="time"]');
days = 1;
$(activityField).change(function () {
activitySelected = $(this).val();
});
$(periodCheckbox).change(function () {
if ($(this).prop("checked")) {
periodselected = true;
}
else
{
periodselected = false;
}
});
$(dateField).change(function () {
if (periodselected) {
startdate = parseDate($(this).val());
enddate = parseDate($(endDateField).val());
} else {
days = 1;
}
;
});
$(endDateField).change(function () {
startdatestring = $(dateField).val();
enddatestring = $(this).val();
startdate = parseDate(startdatestring);
enddate = parseDate(enddatestring);
});
$(plannedHours).off("focusin");
$(plannedHours).focusin(function () {
if (activitySelected === holidayid) {
if (periodselected) {
days = calcBusinessDays(startdate, enddate);
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
} else
{
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
}
}
});
}
});
} else {
j = 0;
$(popupBody).find(".dialog-panel-body").each(function () {
if ($(this).is(":visible")) {
opened = j;
formOpened = $(this).find('form');
}
j++;
});
if (selected === opened) {
activityField = $(formOpened).find('.tempo-activity-picker.select');
periodCheckbox = $(formOpened).find('.showperiod.tempo-show-period');
dateField = $(formOpened).find(' input[name="date"]');
endDateField = $(formOpened).find('input[name="enddate"]');
plannedHours = $(formOpened).find('input[name="time"]');
days = 1;
$(activityField).change(function () {
activitySelected = $(this).val();
});
$(periodCheckbox).change(function () {
if ($(this).prop("checked")) {
periodselected = true;
}
else
{
periodselected = false;
}
});
$(dateField).change(function () {
if (periodselected) {
startdate = parseDate($(this).val());
enddate = parseDate($(endDateField).val());
} else {
days = 1;
}
;
});
$(endDateField).change(function () {
startdatestring = $(dateField).val();
enddatestring = $(this).val();
startdate = parseDate(startdatestring);
enddate = parseDate(enddatestring);
});
$(plannedHours).off("focusin");
$(plannedHours).focusin(function () {
if (activitySelected === holidayid) {
if (periodselected) {
days = calcBusinessDays(startdate, enddate);
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
} else
{
if (holidaysLeft >= days) {
holidaysLeft = holidaysLeft - days;
alert("Mai ai " + holidaysLeft + " zile de concediu ramase!");
$(popupBody).find('button[accesskey="s"]').removeAttr('disabled');
}
else {
$(popupBody).find('button[accesskey="s"]').attr('disabled', 'disabled');
alert('trebuie sa selectezi o perioada mai mica de' + holidaysLeft + 'de zile');
}
}
}
});
}
}
;
}
;
return false;
});
$.ajax({
type: "GET",
url: location.protocol + '//' + location.host + "/rest/api/2/myself",
success: function (response) {
currentUser = $.parseJSON(response);
},
error: function (response) {
alert("Eroare" + response.result);
}
});
return false;
});
});
function calcBusinessDays(dDate1, dDate2) { // input given as Date objects
var iWeeks, iDateDiff, iAdjust = 0;
if (dDate2 < dDate1)
return -1; // error code if dates transposed
var iWeekday1 = dDate1.getDay(); // day of week
var iWeekday2 = dDate2.getDay();
iWeekday1 = (iWeekday1 === 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
iWeekday2 = (iWeekday2 === 0) ? 7 : iWeekday2;
if ((iWeekday1 > 5) && (iWeekday2 > 5))
iAdjust = 1; // adjustment if both days on weekend
iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
// calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000);
if (iWeekday1 <= iWeekday2) {
iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1);
} else {
iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2);
}
iDateDiff -= iAdjust // take into account both days on weekend
return (iDateDiff + 1); // add 1 because dates are inclusive
}
function parseDate(s) {
var lastSlash = s.lastIndexOf("/");
var years = s.substring(lastSlash + 1);
years = "20" + years;
s = s.replaceAt(lastSlash + 1, years);
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = s.replace(pattern, function (match, p1, p2, p3) {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return (months.indexOf(p2) + 1) + "/" + (p1) + "/" + p3;
});
return new Date(result);
}
String.prototype.replaceAt = function (index, character) {
return this.substr(0, index) + character + this.substr(index + character.length);
};
function propStopped(event) {
var msg = "";
if (event.isPropagationStopped()) {
msg = "called";
} else {
msg = "not called";
}
alert(msg);
}
Thanks.
Did you mean this?
Event.prototype.stopPropagation = function(){ alert('123') }
$('input').on('click',function(e){
e.stopPropagation();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='button' value='click' />
From the question, it is unclear as to which code you control. I am reading between the lines that perhaps you control the function bound to the click event for the button, but you do not control the function bound to the focusout event, which is why you need to work around those calls.
If you want to control of execution of the events and make sure that yours happen first, it's possible to do this with something like jQuery.bindUp, just so long as the events are of the same type. In that way, you don't care if the other handler tries to call stopPropagation etc. because your handler will get to execute first anyway.
Given that, is it possible to restructure your code so that the logic you control (the part which needs to happen first!) is of the same event type as the existing event handler, and then use jQuery.bindUp to ensure that it gets executed before the event handler that you do not control? You can still bind to the click event if you need it, just so long as the dependent business logic is moved to the focusout event.
(If my assumptions are not correct, it would be helpful if you could update the question to describe the problem constraints in more detail.)

JavaScript countdown timer not starting

I tried using this JavaScript countdown timer on my page but the timer won't start.
What am I doing wrongly?
var CountdownID = null;
var start_msecond = 9;
var start_sec = 120;
window.onload = countDown(start_msecond, start_sec, "timerID");
function countDown(pmsecond, psecond, timerID) {
var msecond = ((pmsecond < 1) ? "" : "") + pmsecond;
var second = ((psecond < 9) ? "0": "") + psecond;
document.getElementById(timerID).innerHTML = second + "." + msecond;
if (pmsecond == 0 && (psecond-1) < 0) { //Recurse timer
clearTimeout(CountdownID);
var command = "countDown("+start_msecond+", "+start_sec+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
alert("Time is Up! Enter your PIN now to subscribe!");
}
else { //Decrease time by one second
--pmsecond;
if (pmsecond == 0) {
pmsecond=start_msecond;
--psecond;
}
if (psecond == 0) {
psecond=start_sec;
}
var command = "countDown("+pmsecond+", "+psecond+", '"+timerID+"')";
CountdownID = window.setTimeout(command, 100);
}
}
<span style="color:red" name="timerID" id="timerID">91.6</span>
here is what you need to do first
window.onload = countDown(start_msecond, start_sec, "timerID");
should be
window.onload = function () {
countDown(start_msecond, start_sec, "timerID");
}
also you should avoid using a string in your setTimeout function:
CountdownID = window.setTimeout(function () {
countDown(pmsecond,psecond,"timerID");
}, 100);
See here http://jsbin.com/ifiyad/2/edit

Categories

Resources