Have I missed something in JS? - javascript

I have a js coding here, but it doesnt work. What is wrong with it?
Am i missing any {}? or what have I written wrong?
window.addEventListener("load", showPage);
function showPage()
console.log("showPage");
document.getElementById('horizontal1').style.animation = 'mymoveHor 1s';
document.getElementById('horizontal2').style.animation = 'mymoveHor 0.5s';
document.getElementById('vertical1').style.animation = 'mymoveVer 1.5s';
var dfade = document.getElementById("portfolio1");
function fadeIn(dfade, time) {
dfade.style.opacity = 0;
var last = +new Date();
var tick = function () {
dfade.style.opacity = +dfade.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+dfade.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
fadeIn(dfade, 3000);
please help me out...

Just add "{" and "}" to your showPage function
function showPage() {
console.log("showPage");
document.getElementById('horizontal1').style.animation = 'mymoveHor 1s';
document.getElementById('horizontal2').style.animation = 'mymoveHor 0.5s';
document.getElementById('vertical1').style.animation = 'mymoveVer 1.5s';
}
function fadeIn(time) {
var dfade = document.getElementById("portfolio1");
dfade.style.opacity = 0;
var last = +new Date();
var tick = function () {
dfade.style.opacity = +dfade.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+dfade.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
window.addEventListener("load", showPage);
fadeIn(dfade, 3000);

Related

Cannot get content of div to store locally and load locally

I have a JS function to save and load content of a notepad I've made, locally.
I tried to replicate this for a div which contains times of a stopwatch.(see code below)
The stopwatch when paused will write it's time to this div to be saved, I want these times to save when I refresh / close and reopen the page.
It works for my notes in the notepad, please can someone explain where I'm going wrong?
JavaScript for save function:
//Storage of Text-Box
const notesInput = document.querySelector('#notes');
function remFunc() {
// store the entered name in web storage
localStorage.setItem('notes', notes.value);
}
function loadfunc() {
if(localStorage.getItem('notes')) {
let notes_var = localStorage.getItem('notes');
notes.value= notes_var;
} else {
}
}
document.body.onload = loadfunc();
//Storage of Times DIV
const output = document.querySelector('#output');
function remfunc2() {
localStorage.setItem('output', outContent.innerHTML);
}
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
output.innerHTML = output_var ;
} else {
}
}
document.body.onload = loadfunc2();
This is the div:
<div id="output" name="output" class="buttonZ logPad"></div>
Here is the stopwatch Javascript:
// Timer JS
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
function startstop()
{
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if(flagclock==0)
{
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
}
else
{
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
logTime();
}
}
function counter(starttime)
{
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if(flagstop == 1)
{
timediff = timediff + stoptime
}
if(flagclock == 1)
{
clock.innerHTML = formattime(timediff,'');
clock.setAttribute('value', formattime(timediff, ''));
refresh = setTimeout('counter(' + starttime + ');',10);
}
else
{
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime,roundtype)
{
if(roundtype == 'round')
{
var ds = Math.round(rawtime/100) + '';
}
else
{
var ds = Math.floor(rawtime/100) + '';
}
var sec = Math.floor(rawtime/1000);
var min = Math.floor(rawtime/60000);
ds = ds.charAt(ds.length - 1);
if(min >= 60)
{
startstop();
}
sec = sec - 60 * min + '';
if(sec.charAt(sec.length - 2) != '')
{
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
}
else
{
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if(min.charAt(min.length - 2) != '')
{
min = min.charAt(min.length - 2)+min.charAt(min.length - 1);
}
else
{
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
function resetclock()
{
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
if(flagclock !== 0) {
startstopbutton.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
if(flagclock == 1)
{
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
}
else
{
clock.innerHTML = "00:00:0";
}
}
//Split function
function splittime()
{
if(flagclock == 1)
{
if(splitdate != '')
{
var splitold = splitdate.split(':');
var splitnow = clock.innerHTML.split(':');
var numbers = new Array();
var i = 0
for(i;i<splitold.length;i++)
{
numbers[i] = new Array();
numbers[i][0] = splitold[i]*1;
numbers[i][1] = splitnow[i]*1;
}
if(numbers[1][1] < numbers[1][0])
{
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if(numbers[2][1] < numbers[2][0])
{
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
}
splitdate = clock.innerHTML;
output.innerHTML += (++splitcounter) + '. ' + clock.innerHTML + '\n';
}
}
function logTime() {
const time = document.getElementById('clock').getAttribute('value');
document.getElementById('output').innerHTML += (++splitcounter) + '. ' + time + '<br />';
}
function time() {
splittime();
resetclock();
}
Any help will be much appreciated! Thank you.
Okay, so I figured out what I was doing wrong.
The 'output' variable was being used in the timer code.
This prevented me from setting the variable correctly.
I changed the id for the div and the variable name i was using.
I ran this code in my console on this page and it is working:
let counter = 0;
const outContent = document.querySelector('#notify-container');
setInterval(function()
{
counter++;
outContent.innerHTML = `${counter*2} seconds`;
localStorage.setItem('output', outContent.innerHTML);
}, 2000);
function loadfunc2() {
if(localStorage.getItem('output')) {
let output_var = localStorage.getItem('output');
outContent.innerHTML = output_var ;
counter = parseInt(outContent.innerHTML.split(' ')[0], 10)
}
}
loadfunc2()
Paste it into the console, run it, leave it for a few seconds, then refresh the page, paste it and run it again. You can see it working.

trying to create timer for quiz

var myVar = setInterval(function() {
myTimer()
}, 1000);
var d = 1;
function myTimer() {
document.getElementById("demo").innerHTML = d++;
}
Can any one help me how to set the dynamic timer in JavaScript?
I'm trying to create a quiz application and I need to run a timer for the questions which is already available in the database.
I have to retrieve a time from the database and I have to run a count-down timer.
What about something like this. It doesn't reply on the timer being perfect.
var running = false;
var timeToRun = 10000; // 10 seconds
var startTime;
var timer;
var output = document.getElementById("output");
function start(){
running = true;
startTime = new Date();
timer = setInterval(check, 100);
output.innerHTML = "Started<br>" + output.innerHTML;
}
function stop(){
running = false;
clearInterval(timer);
}
function check(){
var now = new Date();
var left = (startTime - now) + timeToRun;
output.innerHTML = left + "<br>" + output.innerHTML;
if (left < 0){
stop();
output.innerHTML = "times up <br>" + output.innerHTML;
}
}
start();
<div id="output">o</div>
function myTimer(d) {
d++;
document.getElementById("demo").innerHTML = d;
return d;
}
var d = 1;
var myVar = setInterval(function() {
d = myTimer(d);
}, 1000);
like this?
[Edit after reading comments:]
var endpoint = [php_timestamp_here];
var countdown = setInterval(function() {
var d = new Date();
var ts = d.getTime();
if( ts >= endpoint ){
// stuff after reach the point...
clearInterval(countdown);
}
// stuff every second
}, 1000);

How to Pause the timer on window blur and resume the timer on window focus event?

Thanks for seeing my question.
I am using wp-pro-quiz plugin for quiz. I want to know that how can I pause the timer if the window is not in focus or is blur and resume it when it is back to focus.?
My code:
I get reset when it get focused
var timelimit = (function () {
var _counter = config.timelimit;
var _intervalId = 0;
var instance = {};
instance.stop = function () {
if (_counter) {
window.clearInterval(_intervalId);
globalElements.timelimit.hide();
}
};
instance.start = function () {
var x;
var beforeTime;
if (!_counter)
return;
var $timeText = globalElements.timelimit.find('span').text(plugin.methode.parseTime(_counter));
var $timeDiv = globalElements.timelimit.find('.wpProQuiz_progress');
globalElements.timelimit.show();
$.winFocus(function (event) {
console.log("Blur\t\t", event);
},
function (event) {
console.log("Focus\t\t", event);
x = _counter * 1000;
beforeTime = +new Date();
});
_intervalId = window.setInterval(function () {
var diff = (+new Date() - beforeTime);
var elapsedTime = x - diff;
if (diff >= 500) {
$timeText.text(plugin.methode.parseTime(Math.ceil(elapsedTime / 1000)));
}
$timeDiv.css('width', (elapsedTime / x * 100) + '%');
if (elapsedTime <= 0) {
instance.stop();
plugin.methode.finishQuiz(true);
}
}, 16);
};
return instance;
})();
Use this wrapper function to pause, resume your timeout.
var Timer;
Timer = function(callback, delay) {
var remaining, start, timerId;
timerId = void 0;
start = void 0;
remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date - start;
};
this.resume = function() {
start = new Date;
window.clearTimeout(timerId);
timerId = window.setTimeout(callback, remaining);
};
this.resume();
};
Intialize it like this, timer = new Timer("callback_function_here", 45000)
In this case total time is 45 seconds for the callback and upon event triggers(blur or focus in your case) it will pause or resume the timer accordingly.
timer.pause() //pause the timer
timer.resume() //resume the timer
P.S - Use this function as per the logic of your code. You will have to make the timer calls accordingly in your code
I did it this way:
var time0 ; var setTimeout_Int; var focused = true; var resume_Fun ;
var addTime =0; var addTimeDiff =0;
window.onfocus = function() {
focused = true;
var d = new Date();
addTimeDiff = addTimeDiff +( d.getTime() - addTime );
resume_Fun();
};
window.onblur = function()
{
focused = false;
};
function init()
{
var d = new Date();
time0 = d.getTime();
setTimeout_Int = setTimeout(update, 1000 )
}
function update()
{
clearTimeout(setTimeout_Int);
var d = new Date();
if(focused)
{
if(d.getTime() -(time0+addTimeDiff) < 20000)
{
setTimeout_Int= setTimeout(update, 1000 )
}
}
else
{
addTime = d.getTime();
resume_Fun = update;
}
}
init();

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 timer issue

Try to make a timer like following way:
HTML:
<div id="timer">
<span id="minute" class="dis">00</span> :
<span id="second" class="dis">00</span> :
<span id="milisecond" class="dis">00</span>
</div>
<input type="button" value="Start/Stop" id="startStop" />
<input type="button" value="Reset" id="reset" />
jQuery:
var a = false,
t = null,
ms = 0,
s = 0,
m = 0,
dl = 10,
now = null,
before = new Date(),
El = function(id) { return document.getElementById(id);};
function dsp() {
if(ms++ == 99){
ms = 0;
if(s++ == 59) {
s = 0;
m++;
} else s = s;
} else ms = ms;
El('milisecond').innerHTML = ms
El('second').innerHTML = s < 10 ? '0' + s : s;
El('minute').innerHTML = m < 10 ? '0' + m : m;
}
function r() {
a = true;
var els = document.getElementsByClassName('dis');
ms = s = m = 0;
sw();
for(var i in els) {
els[i].innerHTML = '00';
}
}
function sw() {
a ? clearInterval(t) : t = setInterval(dsp, dl);
a = !a;
}
El('startStop').addEventListener('click', sw, true);
El('reset').addEventListener('click', r, true);
It works just fine. But problem is that it stop execution when window switch or tab change happen. Before submit this question I read this thread, but fail to implement it in my snippet.
Please help me with some solution or suggestion..
Here is the fiddle
Capture the start time (see Marc's comment) and keep track of previous runs (offset):
var a = false;
var dl = 10;
var El = function(id) { return document.getElementById(id);};
var start = null; // starting time of current measurement
var offset = 0; // offset for previous measurement
function dsp() {
var tmp = new Date(new Date() - start + offset ); // calculate the time
var ms = tmp.getMilliseconds();
var m = tmp.getMinutes();
var s = tmp.getSeconds();
El('milisecond').innerHTML = ms;
El('second').innerHTML = s < 10 ? '0' + s : s;
El('minute').innerHTML = m < 10 ? '0' + m : m;
}
function r() {
a = true;
var els = document.getElementsByClassName('dis');
sw();
offset = 0; // Clear the offset
for(var i in els) {
els[i].innerHTML = '00';
}
}
function sw() {
if(a){
// If the timer stops save the current value
offset += (new Date()) - start;
}else
start = new Date();
a ? clearInterval(t) : t = setInterval(dsp, dl);
a = !a;
}
document.getElementById('startStop').addEventListener('click', sw, true);
document.getElementById('reset').addEventListener('click', r, true);
JSFiddle

Categories

Resources