I'm trying to display some set values for my stats on the webpage....
The javascript is:
<script src="****/js/waypoints.min.js" type="text/javascript"></script>
<script>
$.fn.waypoint.defaults = {
context: window,
continuous: false,
enabled: true,
horizontal: false,
offset: 0,
triggerOnce: true
}
$('.facts_waypoint').waypoint(function(direction) {
function count($this){
var current = parseInt($this.html(), 10);
if (current >= 1000000) {current = current +493023;}
else if (current >= 10000) {current = current +43749;}
else if (current >= 1000) { current = current + 7369;}
else { if (current >= 100) { current = current + 197;}
else {current = current + 1}
}
/*current = current + 100; Where 1 is increment */
$this.html(++current);
if(current > $this.data('count')){
$this.html($this.data('count'));
} else {
setTimeout(function(){count($this)}, 50);
}
}
jQuery(".count_one, .count_two, .count_three").each(function() {
jQuery(this).data('count', parseInt(jQuery(this).html(), 10));
jQuery(this).html('0');
count(jQuery(this));
});
});
However, it only displays the first numbers before the commas... I.e. 22,256,244 = 22 will be displayed... So I tried using LocalString:
<script>
var number = 22874098;
number.toLocaleString(); // "22,874,098"
</script>
This failed and just kept increasing..... Also no commas were included.
Can anyone shed any light on how I would get the numbers to stop increasing BUT more importantly - show commas?
Cheers for now!
Edit - Just tried this:
<script>
$.fn.waypoint.defaults = {
context: window,
continuous: false,
enabled: true,
horizontal: false,
offset: 0,
triggerOnce: true
}
$('.facts_waypoint').waypoint(function(direction) {
function count($this){
var current = parseInt($this.text().replace(/[^0-9]/g, ''), 10);
if (current >= 1000000) {current = current +493023;}
else if (current >= 10000) {current = current +43749;}
else if (current >= 1000) { current = current + 7369;}
else { if (current >= 100) { current = current + 197;}
else {current = current + 1}
}
/*current = current + 100; Where 1 is increment */
$this.text(++current);
if(current > $this.data('count')){
$this.text($this.data('count'));
} else {
setTimeout(function(){count($this)}, 50);
}
}
jQuery(".count_one, .count_two, .count_three").each(function() {
jQuery(this).data('count', parseInt(jQuery(this).text(), 10));
jQuery(this).text('0');
count(jQuery(this));
});
});
</script>
For the comma issue, you will need to strip out non-numeric characters from the value before doing the parseInt. I suggest using $this.text() as opposed to $this.html() and using a regular expression on the input.
var current = parseInt($this.text().replace(/,/g, ''), 10);
That will replace only the commas from the input with empty strings leaving you the digits and the decimal separator. Since you are only interested in integers, you can take another approach with the regular expression and remove all non-numeric characters.
var current = parseInt($this.text().replace(/[^0-9]/g, ''), 10);
When parsing or formatting the value of the field you need to strip out or add commas and carry the text() or html() call through the whole code path. I went through the code and adjusted a couple of things to make it a bit more readable and separate out the parsing more clearly. Give the following a try:
$('.facts_waypoint').waypoint(function(direction) {
function parse(text) {
return parseInt(text.replace(/[^0-9]/g, ''), 10);
}
function count($this) {
var current = parse($this.text());
if (current >= 1000000) {
current = current + 493023;
} else if (current >= 10000) {
current = current + 43749;
} else if (current >= 1000) {
current = current + 7369;
} else if (current >= 100) {
current = current + 197;
} else {
current = current + 1;
}
$this.text((++current).toLocaleString());
if (current < $this.data('count')) {
setTimeout(function() {
count($this)
}, 50);
}
}
jQuery(".count_one, .count_two, .count_three").each(function() {
var $this = jQuery(this);
$this.data('count', parse($this.text()));
$this.text('0');
count($this);
});
});
Related
I am making an artificial intelligent agent to play google chromes t-rex game and need help creating a loop for the game to continuously play at the moment to begin the game I have to actually press space.
document.getElementById("botStatus").addEventListener("change", function() {
if (this.checked === true) {
// Activate bot
var INTERVAL = 2;
window.tRexBot = setInterval(function() {
var tRex = Runner.instance_.tRex;
var obstacles = Runner.instance_.horizon.obstacles;
var lengthsize = 0;
var a = 0.1;
var b = 5;
var c = 35;
var d = 160;
var posWidth = 20;
// if (!tRex.jumping && (obstacles.length > 0) && (obstacles[0].xPos + obstacles[0].width) <= ((parseInt(Runner.instance_.currentSpeed - 0.1) - 5) * 34 + 160) && (obstacles[0].xPos + obstacles[0].width) > 20) {
if (!tRex.jumping && (obstacles.length > lengthsize) && (obstacles[0].xPos + obstacles[0].width) <= ((parseInt(Runner.instance_.currentSpeed - a) - b) * c + d) && (obstacles[0].xPos + obstacles[0].width) > posWidth) {
// console.log(obstacles[0].xPos + obstacles[0].width + " | " + ((parseInt(Runner.instance_.currentSpeed - 0.1) - 5) * 34 + 160));
tRex.startJump();
}
}, INTERVAL);
} else {
// Disable bot
clearInterval(tRexBot);
}
});
what I require is for once the Interval ends, I would like it to take the games current speed and distance of obstacles then either increase or decrease the variables I have set into a new interval, so that it will hopefully learn how to get further and further into the game as it picks up speed...
If this sort of makes sense?
A number of changes you could make to improve the code.
1) Extract the code for starting/stopping the bot to their own functions
var INTERVAL = 2;
function startBot(){
var bot = {}; //empty bot info
bot.tRex = Runner.instance_.tRex;
....
bot.posWidth = 20;
bot.interval = setInterval(function() {
if (!bot.tRex.jumping && (bot.obstacles.length > bot.lengthsize) /*...*/) {
tRex.startJump();
}
},INTERVAL);
return bot;
}
function stopBot(bot) {
clearInterval(bot.interval);
}
document.getElementById("botStatus").addEventListener("change", function() {
if (this.checked === true) {
window.bot = startBot();
}
else {
stopBot(window.bot);
}
}
2) pass the config parameters into the "startBot" function so you can more easily change it on the outside.
var config = { posWidth:20,a: 01,...};
startBot(config);
function startBot(config) {
var bot = config;
//....
}
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.
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);
I want to create a slide show of the number of objects in the "SliderArray" array when I click on the button.
The current JSfiddle is available in standalone mode.
When I take the function into the loop, things get messy
var myFunction = function() {
if (counter == 0) {
$('#' + sliderarray[0].slaytarray[counter].id).fadeIn();
frametime = sliderarray[0].slaytarray[counter].frame_time * 1000;
counter++;
} else if (counter == sliderarray[0].slaytarray.length) {
$('#' + sliderarray[0].slaytarray[counter - 1].id).fadeOut();
counter = 0;
frametime = 0;
} else {
$('#' + sliderarray[0].slaytarray[counter - 1].id).fadeOut();
$('#' + sliderarray[0].slaytarray[counter].id).fadeIn();
frametime = sliderarray[0].slaytarray[counter].frame_time * 1000;
counter++;
}
timeout = setTimeout(myFunction, frametime);
}
var timeout = setTimeout(myFunction, frametime);
And here my objects
This is "messy" because you never manipulate the second slider.
I fixed it by using a .forEach on the sliderarray:
var myFunction = function() {
if (counter == 0) {
sliderarray.forEach(function (slider) {
$('#' + slider.slaytarray[counter].id).fadeIn();
frametime = slider.slaytarray[counter].frame_time * 1000;
});
counter++;
} else if (counter == sliderarray[0].slaytarray.length) {
sliderarray.forEach(function (slider) {
$('#' + slider.slaytarray[counter - 1].id).fadeOut();
});
counter = 0;
frametime = 0;
} else {
sliderarray.forEach(function (slider) {
$('#' + slider.slaytarray[counter - 1].id).fadeOut();
$('#' + slider.slaytarray[counter].id).fadeIn();
frametime = slider.slaytarray[counter].frame_time * 1000;
});
counter++;
}
There is still a problem for the frametime because you're only using once when two are needed. I'll just let you look into it.
See updated JSFiddle
I want to implement a text input with the following implementations:
Only allow numbers
Limit numbers from 0 - 255
If an 'illegal' character was entered (non numbers, or over or under 255), the input should get disabled, wait a second, then delete the invalid char, and get back to focus.
I got all that implemented thanks to this answer. There's an issue though. If you enter 35 (that's 'legal'), then move the cursor between 3 and 5, then enter 1, which comes out to 315. That becomes 'illegal' because it's more than 255. So the 5 gets deleted. I don't want the 5 to get removed, I want the 1 to get deleted because that was the last one entered.
But if you enter 31, then 5, 5 should get removed. Basically, I want the last number entered to get deleted when an illegal amount gets inserted.
Also, I want the cursor to go to the position of the last removed character, whether it's a number or letter.
Here's the code:
JSFiddle
function disableInput(el) {
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
if (checks[0]) {
el.value = el.value.replace(/\D/g, '');
}
if (checks[1]) {
el.value = el.value.slice(0, 2);
};
$(el).dequeue("disabled").val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keyup(function(e) {
disableInput(this)
$(this).focus();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number" />
You can use selectionStart and selectionEnd to see where the cursor is in the input and then use those values to remove the correct character.
Fiddle: http://jsfiddle.net/o4bz0wr7/3/
function disableInput(el) {
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
if (checks[0] || checks[1]) {
el.value = el.value.slice(0, el.selectionStart - 1) + el.value.slice(el.selectionEnd);
}
$(el).dequeue("disabled").val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keyup(function(e) {
disableInput(this)
$(this).focus();
});
EDIT: You can set the cursor position using setSelectionRange.
Fiddle: http://jsfiddle.net/o4bz0wr7/7/
function disableInput(el) {
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
var start = el.selectionStart - 1;
if (checks[0] || checks[1]) {
el.value = el.value.slice(0, start) + el.value.slice(el.selectionEnd);
}
$(el).dequeue("disabled").val(el.value).focus();
el.setSelectionRange(start, start);
}, 1000)
}
}
This should work fine with you, however if there is still any problem add it in comment.
Check it out in action here
var which = null;
function disableInput(el, $which) {
console.log(el.value);
var checks = [/\D/g.test(el.value), el.value > 255];
if (checks.some(Boolean)) {
$(el).prop("disabled", true)
.queue("disabled", function() {
$(this).prop("disabled", false)
});
setTimeout(function() {
console.log(String.fromCharCode($which));
el.value = el.value.replace($which, '');
// el.value = el.value.slice(0,el.value.length - 1);
$(el).dequeue("disabled").val(el.value).focus()
}, 1000)
}
}
$('input[name="number"]').keypress(function(e) {
which = String.fromCharCode(e.which);
$(this).focus();
}).keyup(function(){
disableInput(this, which);
})