2 decimal time display on audio player - javascript

For my audio player, how can I display both times in just 2 decimals?
Right now the counter shows ... 0:7, 0:8, 0:9, 0:10, 0:11
But it should be like:
0:07, 0:08, 0:09, 0:10, 0:11
and the total time of the audio file is displayed like: 273.298866
But it should be:
4:13
var duration = document.getElementById('fullDuration');
var currentTime = document.getElementById('currentTime');
duration.innerHTML = mytrack.duration;
mytrack.addEventListener("loadedmetadata",function(){
var minutes = parseInt(mytrack.duration / 60);
var seconds = parseInt(mytrack.duration % 60);
duration.innerHTML = minutes + ':' + seconds;
})
And
function update(){
if(!mytrack.ended){
var playedMinutes = parseInt(mytrack.currentTime/60);
var playedSeconds = parseInt(mytrack.currentTime%60);
currentTime.innerHTML = playedMinutes + ':' + playedSeconds;
var size = parseInt(mytrack.currentTime*barSize/mytrack.duration);
progressBar.style.width = size + "px";
}
else{
currentTime.innerHTML = "0.00";
playButton.style.backgroundImage = 'url(file:///Users/Pier/Desktop/Play%20button.png)';
progressBar.style.width = "0px";
window.clearInterval(updateTime);
}
}

The modern way to do this is with String.padStart, but it doesn't work with IE:
currentTime.textContent = playedMinutes + ':' + playedSeconds.toString().padStart(2, '0');

Related

How to set an alarm in a countdown project while we are using JavaScript?

I am a new learner. I am making a countdown project that gets input from the user and then countdown the time. It rings an alarm after every 5 seconds. But after getting the end-numbers 00:00 it does not stop. It continuously rings the alarm. Please check the code.
<span id="min">00</span>
<span>:</span>
<span id="snd">00</span>
<audio id="myAudio">
<source src="beep-02.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<button class="btn" id="start" onclick="timer.start();">START</button>
<span class="mx-3"></span>
<button class="btn" id="set" onclick="location.href='time-selecter.html';">SET</button>
<script type="text/javascript">
var hh = localStorage.getItem("a")
var mm = localStorage.getItem("b")
var ss = localStorage.getItem("c")
function yourfunction() {
document.getElementById("hr").innerHTML = hh;
document.getElementById("min").innerHTML = mm;
document.getElementById("snd").innerHTML = ss;
}
window.onload = yourfunction;
//timer
var start_time = 0;
var elapsed_time = 0;
var requested_time;
var timer_inter;
var timer = {
start: function() {
start_time = new Date();
requested_time = toMs(document.getElementById('hr').innerHTML, document.getElementById('min').innerHTML, document.getElementById('snd').innerHTML, 0);
timer_inter = setInterval(function() {
elapsed_time = new Date() - start_time;
document.getElementById('time').innerHTML = toTimeFormat(requested_time - elapsed_time + 1000, 'hh:mm:ss');
//+ 1000ms because the seconds are rounded down, so without it when the timer SHOWS 00:00:00, it will have to wait 1s before stopping
if (elapsed_time >= requested_time) {
timer.stop();
timer.end();
}
}, 0);
},
stop: function() {
clearInterval(timer_inter);
},
end: function() {
document.getElementById('time').innerHTML = '00:00';
}
};
var x = document.getElementById("myAudio");
function yourFunction(){
setTimeout(yourFunction, 5000);
x.play();
}
function pausefn(){
x.pause();
x.currentTime = 0;
}
$("#start").click(function(){
yourFunction();
});
/*------------------------------*/
/*UTILITY*/
/*------------------------------*/
function toTimeFormat(t, format) {
function addDigit(n) {
return (n < 10 ? '0':'') + n;
}
var ms = t % 1000;
t = (t - ms) / 1000;
var secs = t % 60;
t = (t - secs) / 60;
var mins = t % 60;
var hrs = (t - mins) / 60;
ms = (ms < 10) ? '00' : (ms < 100) ? '0' + Math.floor(ms / 10) : Math.floor(ms / 10);
if (format === 'hh:mm:ss') {
return addDigit(mins) + ':' + addDigit(secs);
} else if (format === 'mm:ss:msms') {
return addDigit(mins) + ':' + addDigit(secs) + ':' + ms;
}
}
function toMs(h, m, s, ms) {
return (ms + s * 1000 + m * 1000 * 60 + h * 1000 * 60 * 60);
}
</script>
I am making a countdown project. I tried to stop an alarm when countdown at 00:00 time. But it countinousily rings the alarm untill I close the browser.

Stopping timer at end of block using javascript

I am new to this. I have a Qaultrics survey consisting of different blocks; each block with its own timer. What I want to achieve is the following; if participants complete the first block before the given time, the timer on that block will be cleared as they move to the next block where a new timer would start. In the following block, a new timer needs to start.
Any assistance would be greatly appreciated.
Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
var header = document.createElement("div");
header.className = "header"
header.id = "header_1";
var timer = document.createElement("div");
timer.className = "timer";
timer.id = "timer_1";
timer.innerHTML = "Time Remaining: <span id='time'>01:00</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text = ('innerText' in display)? 'innerText' : 'textContent';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 60,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "";}
});
Qualtrics.SurveyEngine.addOnUnload(function()
{
clearInterval(myTimer);
clearInterval(timer);
clearInterval(timer_1);
document.getElementById("timer_1").innerHTML = "";
});
Here is what I did;
On the first question I used the following code
```Qualtrics.SurveyEngine.addOnload(function()
{
var headerCont = document.createElement("div");
headerCont.className = "header-cont";
headerCont.id = "header_container";
var header = document.createElement("div");
header.className = "header"
header.id = "header_1";
var timer = document.createElement("div");
timer.className = "timer";
timer.id = "timer_1";
timer.innerHTML = "Time Remaining: <span id='time'>02:10</span>";
headerCont.appendChild(header);
header.appendChild(timer);
document.body.insertBefore(headerCont, document.body.firstChild);
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
var myTimer = setInterval(function() {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text = ('innerText' in display)? 'innerText' : 'textContent';
display[text] = minutes + ":" + seconds;
if (--timer < 0) {
clearInterval(myTimer);
timeOver();
}
}, 1000);
}
var timerSeconds = 130,
display = document.querySelector('#time');
startTimer(timerSeconds, display);
var timeOver = function() {
document.getElementById("timer_1").innerHTML = "";}
});```
Then in the last question in the block, I used the following code
{
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
Qualtrics.SurveyEngine.setEmbeddedData('timeRemaining',timer);
clearInterval(myTimer); // fairly certain this isn't doing anything
});
});
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
});
Qualtrics.SurveyEngine.addOnUnload(function() {
document.getElementById("header_container").remove();
});```

Are there different ways of controlling the font-weight locally or on an uploaded web page?

We have created a typewriter simulator which controls the font weight depending on how fast you type, it is controlled with some javascript, some jQuery and styled with css. Here's the link.https://www.dynamik.systems/typewriter/
Before we uploaded it to the site we coded everything with the program Brackets and the font is something we created with a much wider weight then the usual ones.
But now, when everything is up and running it doesn't work like it did from when we coded it locally. No code is changed and the font-face is the same. We have tried it in Chrome, Safari and Firefox.
This is how it looks locally loaded:
https://imgur.com/yNxaX8B
This is how it looks now:
https://imgur.com/OpoYxpV
This is with another font that shows that the code is working:
https://imgur.com/HKPxMlm
We only have tried different types of font styles (otf, ttf, wow etc.) because that's the only thing we can come up with.
The jquery and js.
(function($) {
let i = 0;
let lastTime = 0;
const $output = $("#output");
const $content = $('#content');
$(window).on("keypress", function(event) {
// Prevent backspace, enter and escape
if(event.which === 13 || event.which === 8 || event.which === 27) { console.log('No output'); return; }
// Keypress counter
$("span2").text(i += 1 );
// Intervall for scrollbar
setInterval(updateScroll,5000);
// Timer for Key llklkLatency
let currTime = new Date();
let ms = lastTime ? currTime - lastTime : 0;
$output.text(ms + "ms");
lastTime = currTime;
// Fontweight
var fontWeight = ms > 900 ? 100 : 900 / ms * 100;
// Typewriter
var key = event.key;
$content.append('<span style="font-weight:' + fontWeight + '">' + key + '</span>');
//Font-Weight
$("span3").text(fontWeight);
});
})( jQuery );
function updateScroll(){
var element = document.getElementById("content");
element.scrollTop = element.scrollHeight;
}
// Timer
const output = document.querySelector('output');
let timeRead = false;
let now = 0;
let interval = null;
function startTimer() {
let elapsedMil = Date.now() - now;
let mil = (elapsedMil).toFixed(0) % 100;
let sec = Math.floor(elapsedMil/1000) % 60;
let min = Math.floor(elapsedMil/60000) % 60;
let hou = Math.floor(elapsedMil/3600000) % 24;
mil = padTime(mil);
sec = padTime(sec);
min = padTime(min);
hou = padTime(hou);
function padTime(num) {
if (num < 10) {
num = "0" + num;
}
return num;
}
output.textContent = hou + ":" + min + ":" + sec + ":" + mil;
}
window.onload = function () {
now = Date.now();
interval = window.setInterval(startTimer, 10);
};
var timer = new Timer();
timer.start();
timer.addEventListener('secondsUpdated', function (e) {
$('#basicUsage').html(timer.getTimeValues().toString());
});
function myFunction() {
document.body.style.backgroundColor = "white";
document.getElementById("info").style.color = "black";
document.getElementById("content").style.color = "black";
}
function myFunction2() {
document.body.style.backgroundColor = "black";
document.getElementById("info").style.color = "white";
document.getElementById("content").style.color = "white";
}
function myFunction3() {
document.body.style.backgroundColor = "#FF3700";
document.getElementById("info").style.color = "black";
document.getElementById("content").style.color = "black";
}
Beginning of the CSS to call for the font:
#font-face {
font-family: "dynamik";
src: url('https://www.dynamik.systems/wp-content/themes/fonts/DynamikGX.eot') format('opentype'),
url('https://www.dynamik.systems/wp-content/themes/fonts/DynamikGX.ttf') format('truetype'),
url('https://www.dynamik.systems/wp-content/themes/fonts/DynamikGX.woff') format('woff');
}
We expect the font-weight to be as the way when we uploaded it locally.

jquery event delegation won't work

So I have this code.
$("#inputs input.time").mask("00:00:00");
$("#inputs input.time").prop('value', '00:00:00');
Number.prototype.padDigit = function () {
return (this < 10) ? '0' + this : this;
}
$('#display').click(function () {
$('#show').show();
});
$('#inputs').on('focus', 'input.time', function () {
$(this).select();
});
$('#append').click(function () {
$('#inputs').after("<input type='text' value='00:00:00' class='time' name='time2' /><br>");
});
$('#inputs').on('keyup', 'input.time', function (event) {
console.log(event);
var t1 = '00:00:00';
var mins = 0;
var hrs = 0;
var sec = 0;
$('#inputs input.time').each(function () {
t1 = t1.split(':');
var t2 = $(this).val().split(':');
//console.log(Number(t1[1]) + Number(t2[1]))
sec = Number(t1[2]) + Number(t2[2]);
secmns = Math.floor(parseInt(sec / 60));
mins = Number(t1[1]) + Number(t2[1]) + secmns;
minhrs = Math.floor(parseInt(mins / 60));
hrs = Number(t1[0]) + Number(t2[0]) + minhrs;
sec = sec % 60;
mins = mins % 60;
t1 = hrs.padDigit() + ':' + mins.padDigit() + ':' + sec.padDigit()
console.log(t1)
});
if (t1 == 'NaN:NaN:NaN') {
t1 = '00:00:00';
}
$('#total').text(t1);
/*****************subtract time*****************/
//new Date(year, month, day, hours, minutes, seconds, milliseconds)
//problem, if the seconds, mins or hrs of total is bigger than the remaining. Unexpected result
var start = $('#rem').text();
var end = $('#total').text();
s = start.split(':');
e = end.split(':');
var se = Number(s[2]) - Number(e[2]);
var sems = Math.floor(parseInt(sec / 60));
var mi = Number(s[1]) - Number(e[1]) - sems;
var mihr = Math.floor(parseInt(mins / 60));
var hr = Number(s[0]) - Number(e[0]) - mihr;
if (se < 0) {
mi = mi - 1;
se = se + 60;
}
if (mi < 0) {
hr = hr - 1;
mi = mi + 60;
}
var result = hr.padDigit() + ':' + mi.padDigit() + ':' + se.padDigit();
if (result == 'NaN:NaN:' + se) {
result = '00:00:00';
}
$('#remain').text(result);
});
#remain,
#total {
background-color: #333;
width: 60px;
height: 20px;
color: #fff;
padding: 0 10px;
}
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<script src="https://raw.githubusercontent.com/igorescobar/jQuery-Mask-Plugin/master/src/jquery.mask.js"></script>
<button id='display'>Display</button>
<div id='show'>Remaining:
<div id='remain'>01:20:30</div>Total:
<div id='total'>00:00:00</div>
<div id='rem'>01:20:30</div>
<br>
<div id='inputs'>
<input type='text' class='time' />
<button id='append'>+</button>
<br>
</div>
</div>
my problem is that the event on('keyup') works fine with .append and the result run on keyup event but if i use.after instead of .append, the code still works but the result will only show if the keyup event is done on the very first input. if the code above won't run, try my JFiddle . It's just the same code as above.
Hope this is what you want!! You need to use insertAfter and insert it after last input in the #inputs div
$('#append').click(function () {
$("<input type='text' value='00:00:00' class='time' name='time2' />").insertAfter("#inputs input:last");
});
Here is the working DEMO
EDIT - 2
Change as below and it will work:
$('#append').click(function () {
$("#inputs").after("<input type='text' value='00:00:00' class='time' name='time2' /><br/>");
});
$(document).on('keyup', 'input.time', function (event) {
console.log(event);
var t1 = '00:00:00';
var mins = 0;
var hrs = 0;
var sec = 0;
$('input.time').each(function () {
t1 = t1.split(':');
var t2 = $(this).val().split(':');
//console.log(Number(t1[1]) + Number(t2[1]))
sec = Number(t1[2]) + Number(t2[2]);
secmns = Math.floor(parseInt(sec / 60));
mins = Number(t1[1]) + Number(t2[1]) + secmns;
minhrs = Math.floor(parseInt(mins / 60));
hrs = Number(t1[0]) + Number(t2[0]) + minhrs;
sec = sec % 60;
mins = mins % 60;
t1 = hrs.padDigit() + ':' + mins.padDigit() + ':' + sec.padDigit()
console.log(t1)
});
if (t1 == 'NaN:NaN:NaN') {
t1 = '00:00:00';
}
$('#total').text(t1);
/*****************subtract time*****************/
//new Date(year, month, day, hours, minutes, seconds, milliseconds)
//problem, if the seconds, mins or hrs of total is bigger than the remaining. Unexpected result
var start = $('#rem').text();
var end = $('#total').text();
s = start.split(':');
e = end.split(':');
var se = Number(s[2]) - Number(e[2]);
var sems = Math.floor(parseInt(sec / 60));
var mi = Number(s[1]) - Number(e[1]) - sems;
var mihr = Math.floor(parseInt(mins / 60));
var hr = Number(s[0]) - Number(e[0]) - mihr;
if (se < 0) {
mi = mi - 1;
se = se + 60;
}
if (mi < 0) {
hr = hr - 1;
mi = mi + 60;
}
var result = hr.padDigit() + ':' + mi.padDigit() + ':' + se.padDigit();
if (result == 'NaN:NaN:' + se) {
result = '00:00:00';
}
$('#remain').text(result);
});
WORKING DEMO
Basically what you are trying to do is you are inserting the inputs
after the #inputs div and you have written code to accept keyup
which are present inside #inputs div. Since you are giving same
class name to all the inputs where you make changes if you refer
only them it is enough. No need to reach them through their parent
div.

Javascript display date and time in my website using UTC to consider users timezone in javascript

I want to have a timer in my website like a digital clock. It will have a date and a time in it. I have this following code to do it:
var clockID = 0;
function UpdateClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
var tDate = new Date();
var in_hours = tDate.getHours()
var in_minutes=tDate.getMinutes();
var in_seconds= tDate.getSeconds();
if(in_minutes < 10)
in_minutes = '0'+in_minutes;
if(in_seconds<10)
in_seconds = '0'+in_seconds;
if(in_hours<10)
in_hours = '0'+in_hours;
document.getElementById('theTime').innerHTML = ""
+ in_hours + ":"
+ in_minutes + ":"
+ in_seconds;
clockID = setTimeout("UpdateClock()", 1000);
}
function StartClock() {
clockID = setTimeout("UpdateClock()", 500);
}
function KillClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
}
But this code is displaying the current computer time so the time doesn't fit with my timezone. What else do i need to add in my code so that it will display date and time according to my timezone? If the date is on DST, it will show the exact time in DST too.
If you need to use JS only, have a look at
add or subtract timezone difference to javascript Date
For example DEMO
var clockID;
var yourTimeZoneFrom = -7.00; //time zone value where you are at
var d = new Date();
//get the timezone offset from local time in minutes
var tzDifference = yourTimeZoneFrom * 60 + d.getTimezoneOffset();
//convert the offset to milliseconds
var offset = tzDifference * 60 * 1000;
function UpdateClock() {
var tDate = new Date(new Date().getTime()+offset);
var in_hours = tDate.getHours()
var in_minutes=tDate.getMinutes();
var in_seconds= tDate.getSeconds();
if(in_minutes < 10)
in_minutes = '0'+in_minutes;
if(in_seconds<10)
in_seconds = '0'+in_seconds;
if(in_hours<10)
in_hours = '0'+in_hours;
document.getElementById('theTime').innerHTML = ""
+ in_hours + ":"
+ in_minutes + ":"
+ in_seconds;
}
function StartClock() {
clockID = setInterval(UpdateClock, 500);
}
function KillClock() {
clearTimeout(clockID);
}
window.onload=function() {
StartClock();
}
In JS you can get the current timezone offset. You need to make adjustment the offset to desired timeZone.
<div id="theTime"></div>
<script>
var clockID = 0;
var requiredTimeZone = 360; // CST (+6:00 hrs)
function UpdateClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
var tDate = new Date();
var calculatedTime = tDate.getTime() + (tDate.getTimezoneOffset() * 60000) - (requiredTimeZone * 60000);
tDate.setTime(calculatedTime);
var in_hours = tDate.getHours()
var in_minutes=tDate.getMinutes();
var in_seconds= tDate.getSeconds();
if(in_minutes < 10)
in_minutes = '0'+in_minutes;
if(in_seconds<10)
in_seconds = '0'+in_seconds;
if(in_hours<10)
in_hours = '0'+in_hours;
document.getElementById('theTime').innerHTML = ""
+ in_hours + ":"
+ in_minutes + ":"
+ in_seconds;
clockID = setTimeout("UpdateClock()", 1000);
}
function StartClock() {
clockID = setTimeout("UpdateClock()", 500);
}
function KillClock() {
if(clockID) {
clearTimeout(clockID);
clockID = 0;
}
}
StartClock();
</script>
The current browser timezone offset is added to the browser time and then the desired timezone offset is subtracted to get the required time.
Your required timezone needs to be communicated to the browser in some manner for this to work.

Categories

Resources