How to fix Javascript Timer In asp.net(Master Page concept) - javascript

I Am trying to add Javascript timer in my asp.net project, it is implemented and runing as i needed, but if am pressing any key in that it is disappering for me. But Timer is runing.
Js. code
function myTimer(startVal, interval, outputId, dataField) {
this.value = startVal;
this.OutputCntrl = document.getElementById(outputId);
this.currentTimeOut = null;
this.interval = interval;
this.stopped = false;
this.data = null;
var formEls = document.documentElement;
if (dataField) {
for (var i = 0; i < formEls.length - 1; i++) {
if (formEls[i].name == dataField) {
this.data = formEls[i];
i = formEls.length + 1;
}
}
}
myTimer.prototype.go = function () {
if (this.value > 0 && this.stopped == false) {
this.value = (this.value - this.interval);
if (this.data) {
this.data.value = this.value;
}
var current = this.value;
this.OutputCntrl.innerHTML = this.Hours(current) + ':' + this.Minutes(current) + ':' + this.Seconds(current);
this.currentTimeOut = setTimeout("Timer.go()", this.interval);
}
else {
alert('Time Out!');
//window.location('Index.aspx');
}
}
myTimer.prototype.stop = function () {
this.stopped = true;
if (this.currentTimeOut != null) {
clearTimeout(this.currentTimeout);
}
}
myTimer.prototype.Hours = function (value) {
return Math.floor(value / 3600000);
}
myTimer.prototype.Minutes = function (value) {
return Math.floor((value - (this.Hours(value) * 3600000)) / 60000);
}
myTimer.prototype.Seconds = function (value) {
var hoursMillSecs = (this.Hours(value) * 3600000)
var minutesMillSecs = (this.Minutes(value) * 60000)
var total = (hoursMillSecs + minutesMillSecs)
var ans = Math.floor(((this.value - total) % 60000) / 1000);
if (ans < 10)
return "0" + ans;
return ans;
}
}
I'm calling it from button control.
Code
void Page_PreInit(object sender, EventArgs e)
{
string timerVal = Request.Form["timerData"];
if (timerVal != null || timerVal == "")
{
timerVal = timerVal.Replace(",", String.Empty);
timerStartValue = long.Parse(timerVal);
}
}
private Int32 TimerInterval
{
get
{
object o = ViewState["timerInterval"];
if (o != null) { return Int32.Parse(o.ToString()); }
return 50;
}
set { ViewState["timerInterval"] = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
StringBuilder bldr = new StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.lblTimerCount.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
}
void Page_PreRender(object sender, EventArgs e)
{
StringBuilder bldr = new StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.lblTimerCount.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
}
I'M displaying it into Label control.
<asp:Label ID="lblTimerCount" runat="server" Height="27px"
Width="232px"></asp:Label>
In Page_PreInit 'string timerVal' value is coming same after page_load which I'M passing, it starting timer from starting.?
Please correct me.

These are the simple steps you need to follow:
1) upon page load, set the timerinterval on a hidden element
Your html should look like this:
<input type="button" id="btnStartTimer" name="StartTimer" value="Start" />
<input type="hidden" id="hdnInterval" name="Interval" value="50" />
<p>
<label>Show Timer:</label>
<label id="lblOutput"></label>
</p>
$('#YourButtonId').on('click', function(e){e.preventDefault; Timer.Go(); });
Your button js click event should look like this:
$('#btnStartTimer').on("click", function (e) {
e.preventDefault();
var interval = $('#hdnInterval').val();
var timer = new myTimer(0, interfal, "lblOutput", null);
timer.go();
});
Something along those lines. This will make post backs unnecessary

Related

Javascript Timers assistance

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.

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.

Javascript function is not calling from code behind button click

I'M calling javascript function from button click
StringBuilder bldr = new StringBuilder();
bldr.AppendFormat("var Timer = new myTimer({0},{1},'{2}','timerData');", this.timerStartValue, this.TimerInterval, this.txtResult.ClientID);
bldr.Append("Timer.go()");
ClientScript.RegisterStartupScript(this.GetType(), "TimerScript", bldr.ToString(), true);
ClientScript.RegisterHiddenField("timerData", timerStartValue.ToString());
Button code.
<asp:Button ID="Next" runat="server" OnClick="Button1_Click" Text="Next"
Width="58px" />
same code is calling from another button click.
"myTimer" is my javascript function... js code...
<script type="text/javascript">
function myTimer(startVal, interval, outputId, dataField) {
this.value = startVal;
this.OutputCntrl = document.getElementById(outputId);
this.currentTimeOut = null;
this.interval = interval;
this.stopped = false;
this.data = null;
var formEls = document.documentElement;
if (dataField) {
for (var i = 0; i < formEls.length - 1; i++) {
if (formEls[i].name == dataField) {
this.data = formEls[i];
i = formEls.length + 1;
}
}
}
myTimer.prototype.go = function () {
if (this.value > 0 && this.stopped == false) {
this.value = (this.value - this.interval);
if (this.data) {
this.data.value = this.value;
}
var current = this.value;
this.OutputCntrl.innerHTML = this.Hours(current) + ':' + this.Minutes(current) + ':' + this.Seconds(current);
this.currentTimeOut = setTimeout("Timer.go()", this.interval);
}
else {
alert('Time Out!');
//window.location('Index.aspx');
}
}
myTimer.prototype.stop = function () {
this.stopped = true;
if (this.currentTimeOut != null) {
clearTimeout(this.currentTimeout);
}
}
myTimer.prototype.Hours = function (value) {
return Math.floor(value / 3600000);
}
myTimer.prototype.Minutes = function (value) {
return Math.floor((value - (this.Hours(value) * 3600000)) / 60000);
}
myTimer.prototype.Seconds = function (value) {
var hoursMillSecs = (this.Hours(value) * 3600000)
var minutesMillSecs = (this.Minutes(value) * 60000)
var total = (hoursMillSecs + minutesMillSecs)
var ans = Math.floor(((this.value - total) % 60000) / 1000);
if (ans < 10)
return "0" + ans;
return ans;
}
}
Please check updated code..
full Js code i updated now.
If you Used Update Panels Then You can Use:
ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "javascriptFunction();", true);
Other Wise You can Use
ClientScript.RegisterStartupScript
(GetType(),Guid.NewGuid().ToString(), "javascriptFunction();",true);

Toggle class on HTML element without jQuery

I have a section on my website which holds all the content, but I want a "sidebar" with hidden content to smoothly appear from the left at the push of an external button.
CSS transitions can handle the smoothness no problem, and jQuery toggle() can switch between classes to move the hidden div in and out of the screen.
How can I get the same effect without using jQuery?
You can toggle classes using the classList.toggle() function:
var element = document.getElementById('sidebar');
var trigger = document.getElementById('js-toggle-sidebar'); // or whatever triggers the toggle
trigger.addEventListener('click', function(e) {
e.preventDefault();
element.classList.toggle('sidebar-active'); // or whatever your active class is
});
That should do everything you need - if you have more than one trigger I'd recommend using document.querySelectorAll(selector) instead.
You can implement it only by CSS3:
<label for="showblock">Show Block</label>
<input type="checkbox" id="showblock" />
<div id="block">
Hello World
</div>
And the CSS part:
#block {
background: yellow;
height: 0;
overflow: hidden;
transition: height 300ms linear;
}
label {
cursor: pointer;
}
#showblock {
display: none;
}
#showblock:checked + #block {
height: 40px;
}
The magic is the hidden checkbox and the :checked selector in CSS.
Working jsFiddle Demo.
HTML ONLY
You can use <summary>. The following code doesn't have any dependency.
No JavaScript, CSS at all, HTML only.
<div class="bd-example">
<details open="">
<summary>Some details</summary>
<p>More info about the details.</p>
</details>
<details>
<summary>Even more details</summary>
<p>Here are even more details about the details.</p>
</details>
</div>
For more detail, go to MDN official docs.
you can get any element by id with javascript (no jquery) and the class is an attribute :
element.className
so have this as a function:
UPDATE:
since this is becoming a somewhat popular I updated the function to make it better.
function toggleClass(element, toggleClass){
var currentClass = element.className || '';
var newClass;
if(currentClass.split(' ').indexOf(toggleClass) > -1){ //has class
newClass = currentClass.replace(new RegExp('\\b'+toggleClass+'\\b','g'), '')
}else{
newClass = currentClass + ' ' + toggleClass;
}
element.className = newClass.trim();
}
function init() {
animateCSS(document.getElementById("slide"), 250, {
left: function (timePercent, frame) {
var endPoint = 128,
startPoint = 0,
pathLength = endPoint - startPoint,
base = 64, //slope of the curve
currentPos = Math.floor(startPoint + (Math.pow(base, timePercent) - 1) / (base - 1) * pathLength);
return currentPos + "px";
}
}, function (element) {
element.style.left = "128px";
});
};
var JobType = function () {
if (!(this instanceof JobType)) {
return new JobType(arguments[0]);
};
var arg = arguments[0];
this.fn = arg["fn"];
this.delay = arg["delay"];
this.startTime = arg["startTime"];
this.comment = arg["comment"];
this.elapsed = 0;
};
function JobManager() {
if (!(this instanceof JobManager)) {
return new JobManager();
};
var instance;
JobManager = function () {
return instance;
};
JobManager.prototype = this;
instance = new JobManager();
instance.constructor = JobManager;
var jobQueue = [];
var startedFlag = false;
var inProcess = false;
var currentJob = null;
var timerID = -1;
var start = function () {
if (jobQueue.length) {
startedFlag = true;
currentJob = jobQueue.shift();
var startOver = currentJob.delay - ((new Date()).getTime() - currentJob.startTime);
timerID = setTimeout(function () {
inProcess = true;
currentJob.fn();
if (jobQueue.length) {
try {
while ((jobQueue[0].delay - ((new Date()).getTime() - currentJob.startTime)) <= 0) {
currentJob = jobQueue.shift();
currentJob.fn();
};
}
catch (e) { };
}
inProcess = false;
start();
}, (startOver > 0 ? startOver : 0));
}
else {
startedFlag = false;
timerID = -1;
};
};
instance.add = function (newJob) {
if (newJob instanceof JobType) {
stopCurrent();
var jobQueueLength = jobQueue.length;
if (!jobQueueLength) {
jobQueue.push(newJob);
}
else {
var currentTime = (new Date()).getTime(),
insertedFlag = false;
for (var i = 0; i < jobQueueLength; i++) {
var tempJob = jobQueue[i],
tempJobElapsed = currentTime - tempJob["startTime"],
tempJobDelay = tempJob["delay"] - tempJobElapsed;
tempJob["elapsed"] = tempJobElapsed;
if (newJob["delay"] <= tempJobDelay) {
if (!insertedFlag) {
jobQueue.splice(i, 0, newJob);
insertedFlag = true;
}
};
if (i === (jobQueueLength - 1)) {
if (!insertedFlag) {
jobQueue.push(newJob);
insertedFlag = true;
}
}
};
};
if ((!startedFlag) && (!inProcess)) {
start();
};
return true;
}
else {
return false;
};
};
var stopCurrent = function () {
if (timerID >= 0) {
if (!inProcess) {
clearTimeout(timerID);
timerID = -1;
if (currentJob) {
jobQueue.unshift(currentJob);
};
};
startedFlag = false;
};
};
return instance;
};
function animateCSS(element, duration, animation, whendone) {
var frame = 0,
elapsedTime = 0,
timePercent = 0,
startTime = new Date().getTime(),
endTime = startTime + duration,
fps = 0,
averageRenderTime = 1000,
normalRenderTime = 1000 / 25,
myJobManager = JobManager();
var inQueue = myJobManager.add(JobType({
"fn": displayNextFrame,
"delay": 0,
"startTime": (new Date).getTime(),
"comment": "start new animation"
}));
function playFrame() {
for (var cssprop in animation) {
try {
element.style[cssprop] = animation[cssprop].call(element, timePercent, frame);
} catch (e) { }
};
};
function displayNextFrame() {
elapsedTime = (new Date().getTime()) - startTime;
timePercent = elapsedTime / duration;
if (elapsedTime >= duration) {
playFrame();
if (whendone) {
whendone(element);
};
return;
};
playFrame();
frame++;
averageRenderTime = elapsedTime / frame;
fps = 1000 / averageRenderTime;
inQueue = myJobManager.add(JobType({
"fn": displayNextFrame,
"delay": (fps < 15 ? 0 : normalRenderTime - averageRenderTime),
"startTime": (new Date).getTime(),
"comment": frame
}));
}
};
(function () {
if (this.addEventListener) {
this.addEventListener("load", init, false)
}
else {
window.onload = init;
}
}());
// By Plain Javascript
// this code will work on most of browsers.
function hasClass(ele, clsName) {
var el = ele.className;
el = el.split(' ');
if(el.indexOf(clsName) > -1){
var cIndex = el.indexOf(clsName);
el.splice(cIndex, 1);
ele.className = " ";
el.forEach(function(item, index){
ele.className += " " + item;
})
}
else {
el.push(clsName);
ele.className = " ";
el.forEach(function(item, index){
ele.className += " " + item;
})
}
}
var btn = document.getElementById('btn');
var ele = document.getElementById('temp');
btn.addEventListener('click', function(){
hasClass(ele, 'active')
})
I did not test but the code below should work.
<script>
function toggleClass(){
var element = document.getElementById("a");
element.classList.toggle("b");
}
document.getElementById("c").addEventListener('click', toggleClass )
</script>

I want to make countdown then capatcha

Hi
I got countdown code
<script type="text/javascript">
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
</script>
I want when the countdown end appear CAPTCHA or question if this right, then continue to link
try to put the countdown function here
window.onload = function() {
countDown('my_div1', //here// , 10);
}
Assume that your countdown coding is working fine and you have a div in which captcha is stored say div id = "captchadiv",
<script type="text/javascript">
window.onload = function() {
//////////////////////////////////////////////////////
set the visibility of the captcha hidden here.
//////////////////////////////////////////////////////
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
//////////////////////////////////////////////////////
set visibility of captchadiv to visibile.
//////////////////////////////////////////////////////
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
//////////////////////////////////////////////////////
add a function here to validate the captcha.
If validation succeeds, do success action.
If validation fails, set captcha visibility to hidden and again call the counttDown function.
//////////////////////////////////////////////////////
</script>
EDIT
Check this out. (Untested version)
<script type="text/javascript">
var mathenticate;
window.onload = function() {
countDown('my_div1', '<form>1+1=<input name="d" type="text" /></form>', 10);
}
function countDown(elID, output, seconds) {
var elem = document.getElementById(elID),
start = new Date().getTime(), end = start+seconds*1000,
timer = setInterval(function() {
var now = new Date().getTime(), timeleft = end-now, timeparts;
if( timeleft < 0) {
elem.innerHTML = output;
clearInterval(timer);
mathenticate = {
bounds: {
lower: 5,
upper: 50
},
first: 0,
second: 0,
generate: function()
{
this.first = Math.floor(Math.random() * this.bounds.lower) + 1;
this.second = Math.floor(Math.random() * this.bounds.upper) + 1;
},
show: function()
{
return this.first + ' + ' + this.second;
},
solve: function()
{
return this.first + this.second;
}
};
mathenticate.generate();
var $auth = $('<input type="text" name="auth" />');
$auth
.attr('placeholder', mathenticate.show())
.insertAfter('input[name="name"]');
}
else {
timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
elem.innerHTML = "Time left: "+timeparts[1];
}
},250);
}
$('#form').on('submit', function(e){
e.preventDefault();
if( $auth.val() != mathenticate.solve() )
{
alert('wrong answer!');
// If you want to generate a new captcha, then
mathenticate.generate();
}else {
document.location.href = 'http://www.overdir.com';
}
});
</script>

Categories

Resources