Remove Component When Negative - javascript

My goal is to display to the user ONLY the time left in there current period. Currently it displays all of the periods duration and time reaming, I only want to display one, which is the time frame they are currently in.
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '13:31' ],
[ '13:35' , '14:25' ]
];
generatePeriods();
updateTimePeriods();
setTimeout(updateTimePeriods, 1000); // Update every second
function generatePeriods() {
var listEl = document.getElementById('periods');
periods.forEach(function(period) {
listEl.appendChild(document.createElement('LI'));
});
}
function updateTimePeriods() {
var now = new Date();
var children = document.getElementById('periods').childNodes;
var i = 0;
for (var i = 0; i < children.length; i++) {
var child = children[i];
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
}
<div class="outer-box">
<div id="periods"></div>
</div>

You can check the time using the following snippet :
for (var i = 0; i < children.length; i++) {
var child = children[i];
var now = new Date();
var nowHour = now.getHours();
if(periods[i][0] > nowHour) {
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}

First, i have slightly changed your HTML, li should be child of ul.
Then i've removed your generatePeriods() function.
If you don't want to show all periods (just positive) - you don't need empty li elements.
Then i slightly modified your updateTimePeriods() function:
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') { // check if negative
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
So, now it should work like this:
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '15:55' ],
[ '13:35' , '15:56' ]
];
updateTimePeriods();
setInterval(updateTimePeriods, 1000); // Update every second
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
}
<div class="outer-box">
<ul id="periods"></ul>
</div>
P.S. I've updated periods array because of testing.

Related

Disable a day in a datepicker that is not in the list

I have a variable that will receive some data, specifically the day of the week and something else.
let wTime = [{"day":"Mon"},{"day":"Tue"},{"day":"Wed"},{"day":"Fri"},{"day":"Sat"},{"day":"Sun"}]
I also have a bootstrap datepicker, and in it I need to determine which day is not in the wTime variable and disable this day.
How can i do this? Specifically, there is no Th day right now, and for now I manually disable it using daysOfWeekDisabled: '4'
let wTime = [{"day":"Mon"},{"day":"Tue"},{"day":"Wed"},{"day":"Fri"},{"day":"Sat"},{"day":"Sun"}]
let restaurantReserve = {
init: function() {
let _self = this;
let today = new Date().toLocaleString('en-us',{day:'numeric', month:'short'}).split(' ').reverse().join(' ');
$('#reservation-date').datepicker({
startDate: '+0d',
daysOfWeekDisabled: '4'
}).on('changeDate', function(e) {
const arDate = e.date.toString().split(' ');
let input = $('[name="RestaurantReservationForm[date]"]');
input.val(arDate[3] + '-' + (e.date.getMonth() + 1) + '-' + arDate[2]);
_self.unSetError(input);
$('#reservation-date .js-value').text(arDate[2] + ' ' + arDate[1]);
});
$("#reservation-date").datepicker("setDate", today);
},
setError: function(ob) {
$('#' + ob.data('btnId')).addClass('btn-error');
},
unSetError: function(ob) {
$('#' + ob.data('btnId')).removeClass('btn-error');
}
}
restaurantReserve.init();
.btn {
border: none;
border-radius: 8px;
padding: 10px 15px;
font-weight: 800;
font-size: 14px;
cursor: pointer;
}
.btn-fourth {
text-decoration: none;
background: #e3e5e8;
color: #747b8b;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<a class="btn btn-fourth " id="reservation-date" data-date=">">
<span class="icon br-calender"></span> <span class="js-value">click</span>
</a>
Why not make a day checker? If you want to dynamically get rid of a day, simply check to see which day is missing and set that to your daysOfWeekDisabled:
You could do something like this:
let wTime = [{"day":"Tue"},{"day":"Fri"},{"day":"Sat"},{"day":"Sun"}]
let dayCheck = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
let dayNumbers = ''
let disabledDays = dayCheck.filter(y => wTime.map(x => x['day']).every(x => x !== y)).forEach(y => dayNumbers += dayCheck.indexOf(y))
console.log(dayNumbers.split('').join(', '))
EDIT: One issue that has not been clarified is where is the user interacting with wTime. As in, how are you getting the user interaction to decide which day should be omitted? This solution is assuming wTime is somehow being modified through a user interaction. If that part is already decided, then this should work. If you need help with actually setting wTime up to be accessible to user engagement, then we'll need more code.
Full code would look like this:
let wTime = [{"day":"Tue"},{"day":"Fri"},{"day":"Sat"},{"day":"Sun"}]
let dayCheck = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
let dayNumbers = ''
let disabledDays = dayCheck.filter(y => wTime.map(x => x['day']).every(x => x !== y)).forEach(y => dayNumbers += dayCheck.indexOf(y))
let restaurantReserve = {
init: function() {
let _self = this;
let today = new Date().toLocaleString('en-us',{day:'numeric', month:'short'}).split(' ').reverse().join(' ');
$('#reservation-date').datepicker({
startDate: '+0d',
daysOfWeekDisabled: dayNumbers.split('').join(', ')
}).on('changeDate', function(e) {
const arDate = e.date.toString().split(' ');
let input = $('[name="RestaurantReservationForm[date]"]');
input.val(arDate[3] + '-' + (e.date.getMonth() + 1) + '-' + arDate[2]);
_self.unSetError(input);
$('#reservation-date .js-value').text(arDate[2] + ' ' + arDate[1]);
});
$("#reservation-date").datepicker("setDate", today);
},
setError: function(ob) {
$('#' + ob.data('btnId')).addClass('btn-error');
},
unSetError: function(ob) {
$('#' + ob.data('btnId')).removeClass('btn-error');
}
}
restaurantReserve.init();
Enhancing your current function with an Enum that gives us each day correlating to a number. Then simply filter that enum with the wTime array to find the missing days and disable them.
let wTime = [{"day":"Mon"},{"day":"Tue"},{"day":"Wed"},{"day":"Fri"},{"day":"Sat"},{"day":"Sun"}]
let wTimeEnum = {'Mon':'1', 'Tue':'2', 'Wed':'3','Thur':'4', 'Fri':'5', 'Sat':'6', 'Sun':'0'};
let restaurantReserve = {
init: function() {
let _self = this;
let today = new Date().toLocaleString('en-us',{day:'numeric', month:'short'}).split(' ').reverse().join(' ');
$('#reservation-date').datepicker({
startDate: '+0d',
daysOfWeekDisabled: Object.keys(wTimeEnum).filter((k) => wTime.every((d) => d.day != k)).map((k) => wTimeEnum[k])
//daysOfWeekDisabled: ['4']
}).on('changeDate', function(e) {
const arDate = e.date.toString().split(' ');
let input = $('[name="RestaurantReservationForm[date]"]');
input.val(arDate[3] + '-' + (e.date.getMonth() + 1) + '-' + arDate[2]);
_self.unSetError(input);
$('#reservation-date .js-value').text(arDate[2] + ' ' + arDate[1]);
});
$("#reservation-date").datepicker("setDate", today);
},
setError: function(ob) {
$('#' + ob.data('btnId')).addClass('btn-error');
},
unSetError: function(ob) {
$('#' + ob.data('btnId')).removeClass('btn-error');
}
}
restaurantReserve.init();
.btn {
border: none;
border-radius: 8px;
padding: 10px 15px;
font-weight: 800;
font-size: 14px;
cursor: pointer;
}
.btn-fourth {
text-decoration: none;
background: #e3e5e8;
color: #747b8b;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<a class="btn btn-fourth " id="reservation-date" data-date=">">
<span class="icon br-calender"></span> <span class="js-value">click</span>
</a>

Javascript for loop innerhtml doesn't work

class GenerateArray {
constructor() {
this.arrayCode = document.getElementById('code');
this.BaseCode = document.getElementById('preCode');
this.startCode = document.getElementById('startC');
this.endCode = document.getElementById('endC');
this.question = "";
this.prefix = "";
this.description = "";
this.answer = "";
this.id = "";
this.Name = "";
this.answerDIV = "";
this.count = 0;
}
generateQuestionPart() {
this.question = document.createElement('input');
this.question.setAttribute('type', 'text');
this.question.id = 'question' + this.count;
this.question.className = 'question';
this.question.placeholder = 'What is the question?'
this.prefix = document.createElement('input');
this.prefix.setAttribute('type', 'text');
this.prefix.className = 'prefix';
this.prefix.id = 'prefix' + this.count;
this.prefix.placeholder = 'The prefix of the question that belongs to the link'
this.description = document.createElement('input');
this.description.setAttribute('type', 'text');
this.description.id = 'description' + this.count;
this.description.className = 'description';
this.description.placeholder = 'Add the description that is going to be in the info pop up';
this.answerDIV = document.createElement('div');
this.answerDIV.className = 'answerDIV' + this.count;
this.answerDIV.id = 'AnswerDivId';
this.answer = document.createElement('button');
this.answer.setAttribute('type', 'button');
this.answer.id = 'answer';
this.answer.className = 'answerN' + this.count;
this.answer.innerHTML = 'Add Answer';
this.answer.onclick = function (e) {
for (let i = 0; i < NewArray.count; i++) {
if (e.target.className.endsWith(i)) {
NewArray.id = document.createElement('input');
NewArray.id.setAttribute('type', 'text');
NewArray.id.id = 'id' + i;
NewArray.id.classList.add('id');
NewArray.id.placeholder = 'Add the ID of the answer';
NewArray.Name = document.createElement('input');
NewArray.Name.setAttribute('type', 'text');
NewArray.Name.id = 'Name' + i;
NewArray.Name.className = 'name';
NewArray.Name.placeholder = 'Add the text that is on the answer button';
// console.log(e.target.className);
document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.id);
document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.Name);
}
}
}
document.getElementsByClassName('create')[0].appendChild(this.question);
document.getElementsByClassName('create')[0].appendChild(this.prefix);
document.getElementsByClassName('create')[0].appendChild(this.description);
document.getElementsByClassName('create')[0].appendChild(this.answerDIV);
document.getElementsByClassName('create')[0].appendChild(this.answer);
this.count++;
// console.log(NewArray.answer.length)
}
writeArray() {
let basis = document.createElement('p');
basis.innerHTML =
" class QuizPart {\n" +
" constructor(questionText, chosenAnswer, prefix, questionDescription) {\n" +
" this.questionText = questionText;\n" +
" this.chosenAnswer = chosenAnswer;\n" +
" this.prefix = prefix;\n" +
" this.questionDescription = questionDescription;\n" +
" }\n" +
" }\n" +
"\n" +
" class ChosenAnswer {\n" +
" constructor(id, name) {\n" +
" this.id = id;\n" +
" this.name = name;\n" +
" }\n" +
" }";
this.BaseCode.appendChild(basis);
let startC = document.createElement('p');
startC.innerHTML = "let Quiz = [";
for (let i = 0; i < this.count; i++) {
let code = document.createElement('p');
let output = "new QuizPart('" + document.getElementById('question' + i).value + "', [";
let answers = document.querySelectorAll("input#Name" + i)
console.log(answers.length);
for (let y = 0; y < answers.length; y++) {
output += "new ChosenAnswer('" + document.getElementById('id' + i).value + "', '" + document.getElementById('Name' + i).value + "'),"
}
output += "], '" + document.getElementById('prefix' + i).value + "',";
output += "'" + document.getElementById('description' + i).value + "',";
code.innerHTML = output;
this.arrayCode.appendChild(code);
}
let endC = document.createElement('p');
endC.innerHTML = "]"
this.startCode.appendChild(startC);
this.endCode.appendChild(endC);
// console.log(this.count.length);
}
}
NewArray = new GenerateArray();
NewArray.generateQuestionPart();
body {
margin: 0;
padding: 0;
}
.container{
height: 1000px;
width: 800px;
position: relative;
margin-top: 5px;
left: 50%;
-ms-transform: translate(-50%, 5%);
transform: translate(-50%, 5%);
}
.QPB{
width: 50px;
height: 50px;
margin-bottom: 10px;
background-color: orange;
font-size: 40px;
}
.question{
width: 100%;
height: 20px;
margin-bottom: 10px;
}
#answer{
width: 100px;
height: 35px;
margin-bottom: 50px;
}
.prefix{
width: 100%;
height: 20px;
margin-bottom: 10px;
}
.description{
width: 100%;
height: 20px;
margin-bottom: 10px;
}
.id{
position: relative;
width: 90%;
height: 20px;
margin-bottom: 10px;
margin-left: 10%;
}
.name{
position: relative;
width: 90%;
height: 20px;
margin-bottom: 20px;
margin-left: 10%;
}
.CreateArray{
width: 100px;
height: 35px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="./style.css">
<title>Hoi</title>
</head>
<body>
<div class="container">
<div class="create">
<button id="QuestionPartBtn" class="QPB" type="button" onclick="NewArray.generateQuestionPart()">+</button>
</div>
<div class="result">
<button id="CreateArray" class="CreateArray" type="button" onclick="NewArray.writeArray()">Create Array</button>
</div>
<div class="preCode" id="preCode"></div>
<div class="startC" id="startC"></div>
<div class="code" id="code"></div>
<div class="endC" id="endC"></div>
</div>
I created this system that makes an array with information that a user fills in in input fields.
The input fields are dynamically generated, so I use a for loop to show them all in an innerHTML that eventually creates the array.
My code:
this.answerDIV = document.createElement('div');
this.answerDIV.className = 'answerDIV' + this.count;
this.answerDIV.id = 'AnswerDivId';
this.answer = document.createElement('button');
this.answer.setAttribute('type', 'button');
this.answer.id = 'answer';
this.answer.className = 'answerN' + this.count;
this.answer.innerHTML = 'Add Answer';
this.answer.onclick = function (e) {
for (let i = 0; i < NewArray.count; i++) {
if (e.target.className.endsWith(i)) {
NewArray.id = document.createElement('input');
NewArray.id.setAttribute('type', 'text');
NewArray.id.id = 'id' + i;
NewArray.id.classList.add('id');
NewArray.id.placeholder = 'Add the ID of the answer';
NewArray.Name = document.createElement('input');
NewArray.Name.setAttribute('type', 'text');
NewArray.Name.id = 'Name' + i;
NewArray.Name.className = 'name';
NewArray.Name.placeholder = 'Add the text that is on the answer button';
// console.log(e.target.className);
document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.id);
document.getElementsByClassName('answerDIV' + i)[0].appendChild(NewArray.Name);
}
}
}
For loop:
for (let i = 0; i < this.count; i++) {
let code = document.createElement('p');
let output = "new QuizPart('" + document.getElementById('question' + i).value + "', [";
let answers = document.querySelectorAll("input#Name" + i)
console.log(answers.length);
for (let y = 0; y < answers.length; y++) {
output += "new ChosenAnswer('" + document.getElementById('id' + i).value + "', '" + document.getElementById('Name' + i).value + "'),"
}
output += "], '" + document.getElementById('prefix' + i).value + "',";
output += "'" + document.getElementById('description' + i).value + "',";
code.innerHTML = output;
this.arrayCode.appendChild(code);
}
The problem is with the second loop. Whenever I create 3 input fields for one question and I generate the innerHTML code it does show me all 3, except that they are all the first input field and the second and third aren't used as seen in the following screenshot:The problem
if i change i to y: Problem 2
(My FiddleJS link):https://jsfiddle.net/thijsl0705/1s98gumk/1/
I entered a,b,c then add answer, d,e then hit the plus sign and add f,g,h,i,j then create array. then hit the plus sign and add 1,2,3,4,5 and create the array and get:
let Quiz = [
let Quiz = [
new QuizPart('a', [new ChosenAnswer('d', 'e'),], 'b','c',
new QuizPart('f', [new ChosenAnswer('i', 'j'),], 'g','h',
new QuizPart('a', [new ChosenAnswer('d', 'e'),], 'b','c',
new QuizPart('f', [new ChosenAnswer('i', 'j'),], 'g','h',
new QuizPart('1', [new ChosenAnswer('4', '5'),], '2','3',
]
]
what exactly is the problem? what do you want to do? Looks like you might be missing a closing ) for each new QuizPart

How could I add some HTML/Text into a Javascript text output? I can only seem to either only do JS or only text, not both

I am currently trying to design a scrolling command prompt with JS and HTML. Unfortunately I cannot find a way to output text and a JavaScript variable on the same line. I feel like I have tried a million things.
var textarea = $('.term');
var speed = 50; //Writing speed in milliseconds
var text = 'TEST';
var java = '282828'
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function() {
if (i < text.length)
runner();
else {
textarea.append("<br>")
i = 0;
setTimeout(function() {feedbacker();}, 1000);
}
}, Math.floor(Math.random() * 220) + 50);
}
var count = 0;
var time = 5;
function feedbacker() {
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
if (time % 10 == 0) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
if (time == 3) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
window.scrollTo(0, document.body.scrollHeight);
i++;
time = Math.floor(Math.random() * 1000) + 1000;
count += time;
setTimeout(
function() {
if (i < output.length - 2)
feedbacker();
else {
textarea.append("<br>Initialising...<br>");
setTimeout(function() {$(".load").fadeOut(1000);}, 1000000);
}
},time);
}
var output = [
"Below is a vat test",
"number" (java),
"Hello",
(java),
"Above is a test",
"Initialising...",
""];
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
<pre class="term">dev:~$ </pre>
</div>
This outputs correctly but any time I try to add text it fails. For example:
"number" (java),
"number", (java),
"number (java)",
"number '(java)'",
I think this output may be broken because it's a textarea. I am not sure. I would love to learn and get this figured out. Much appreciated!
var output = [
"Below is a vat test",
"number" (java),
"Hello",
(java),
"Above is a test",
"Initialising...",
""];
"number" (java) and (java) are not the correct way to display Javascript Variables.
You use simply java, or use + to concatenate two strings together such as "number" + java. You could be fancier with Template literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals:
var output = [
"Below is a vat test",
`number ${java}`,
"Hello",
java,
"Above is a test",
"Initialising...",
""];
Just use concatenation (+) to append a JavaScript variable to static content.
var textarea = $('.term');
var speed = 50; //Writing speed in milliseconds
var text = 'TEST';
var java = '282828'
var i = 0;
runner();
function runner() {
textarea.append(text.charAt(i));
i++;
setTimeout(
function() {
if (i < text.length)
runner();
else {
textarea.append("<br>")
i = 0;
setTimeout(function() {feedbacker();}, 1000);
}
}, Math.floor(Math.random() * 220) + 50);
}
var count = 0;
var time = 5;
function feedbacker() {
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
if (time % 10 == 0) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
if (time == 3) {
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
i++;
textarea.append("[ " + count / 1000 + "] " + output[i] + "<br>");
}
window.scrollTo(0, document.body.scrollHeight);
i++;
time = Math.floor(Math.random() * 1000) + 1000;
count += time;
setTimeout(
function() {
if (i < output.length - 2)
feedbacker();
else {
textarea.append("<br>Initialising...<br>");
setTimeout(function() {$(".load").fadeOut(1000);}, 1000000);
}
},time);
}
var output = [
"Below is a vat test",
"number (" + java + ")",
"Hello",
"(" + java + ")",
"Above is a test",
"Initialising...",
""];
html,
body {
margin: 0 auto;
height: 100%;
}
pre {
padding: 0;
margin: 0;
}
.load {
margin: 0 auto;
min-height: 100%;
width: 100%;
background: black;
}
.term {
font-family: monospace;
color: #fff;
opacity: 0.8;
font-size: 2em;
overflow-y: auto;
overflow-x: hidden;
padding-top: 10px;
padding-left: 20px;
}
.term:after {
content: "_";
opacity: 1;
animation: cursor 1s infinite;
}
#keyframes cursor {
0% {
opacity: 0;
}
40% {
opacity: 0;
}
50% {
opacity: 1;
}
90% {
opacity: 1;
}
100% {
opacity: 0;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="load">
<pre class="term">dev:~$ </pre>
</div>

JavaScript Time Exception Message

I'm currently working on a script that displays the amount of time until a period ends or starts in my school. One of the data sets in the array needs to be excluded from being counted as a period.
{ start: minutes(11, 20), end: minutes(11, 46) },
I want to exclude this data because its not a full fledged period, its lunch, and im not sure how I should go about doing it. Any ideas? Also the message would need to be changed to the user instead of.
document.getElementById("result").innerHTML = "There are " + timeLeft + " minutes left until period " + (i+1) + " is over."
Any ideas?
body, html {
height: 100%;
}
body {
background-color: #a00000;
margin: 0; /* remove default margins added by browsers */
}
.wrapper {
display: flex;
height: 100%;
}
#result {
margin: auto;
padding: 25px;
font-weight: bold;
text-align: center;
color:black;
width: 250px;
border-radius: 10px;
background-color: white;
}
h1 {
font-weight: bold;
margin:auto;
font-size: 20px;
}
.lunch {
width: 95px;
background-color: #a00000;
color: white;
border: 1px solid black;
border-radius: 5px;
padding: 5px;
margin-top: 10px;
}
<html>
<head>
<meta charset="UTF-8">
<title>Marking Period Countdow</title>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body onload="myFunction(myTime, periods);">
<script>
//Get current date & midnight
var now = new Date();
var midnight = new Date();
midnight.setHours(0,0,0,0);
//Get number of minutes that passed since midnight:
var myTime = Math.floor((now.getTime() - midnight.getTime()) / 60000);
//For Testing Purposes.
// console.log(myTime + ' minutes passed since midnight.');
function minutes(hour, min) {
return hour * 60 + min;
}
//All the periods throughout my school day.
var periods = [
{ start: minutes( 7, 45), end: minutes( 8, 34) },
{ start: minutes( 8, 38), end: minutes( 9, 30) },
{ start: minutes( 9, 34), end: minutes(10, 23) },
{ start: minutes(10, 27), end: minutes(11, 16) },
{ start: minutes(11, 20), end: minutes(12, 09) },
{ start: minutes(12, 12), end: minutes(12, 38) },
{ start: minutes(12, 42), end: minutes(13, 31) },
{ start: minutes(13, 35), end: minutes(14, 25) },
];
function myFunction(myTime, periods) {
periods.every(function (period, i) {
if (myTime < period.start) {
if (i == 0) {
console.log('School has not started yet');
document.getElementById("result").innerHTML = "School has not started yet";
} else {
var timeLeft = period.start - myTime;
console.log("There are " + timeLeft + " minutes left until period " + (i+1) + " starts.");
document.getElementById("result").innerHTML = "There are " + timeLeft + " minutes left until period " + (i+1) + " starts.";
}
} else if (myTime < period.end) {
var timeLeft = period.end - myTime;
console.log("There are " + timeLeft + " minutes left until period " + (i+1) + " is over.");
document.getElementById("result").innerHTML = "There are " + timeLeft + " minutes left until period " + (i+1) + " is over.";
} else if (i == periods.length - 1) {
console.log('School has finished for today');
document.getElementById("result").innerHTML = "School has finished for today";
} else {
return true; // keep looking for the right period
}
});
}
</script>
<div class="wrapper">
<div id="result"></div>
</div>
</body>
</html>
If you want to make it more functional, you can create functions for your messages and then let the periods themselves define which messages they should display. Like the following.
//Get current date & midnight
var now = new Date();
var midnight = new Date();
midnight.setHours(0, 0, 0, 0);
//Get number of minutes that passed since midnight:
var myTime = Math.floor((now.getTime() - midnight.getTime()) / 60000);
function minutes(hour, min) {
return hour * 60 + min;
}
function defaultMessage(minutes, i) {
document.getElementById("result").innerHTML = "There are " + minutes + " minutes left until period " + (i + 1) + " is over.";
};
function lunchMessage(minutes, i) {
document.getElementById("result").innerHTML = "Lunch will end in " + minutes + " minutes";
};
//All the periods throughout my school day.
var periods = [{
start: minutes(7, 45),
end: minutes(8, 34),
message: defaultMessage
}, {
start: minutes(8, 38),
end: minutes(9, 30),
message: defaultMessage
}, {
start: minutes(9, 34),
end: minutes(10, 23),
message: defaultMessage
}, {
start: minutes(10, 27),
end: minutes(11, 16),
message: defaultMessage
}, {
start: minutes(11, 20),
end: minutes(12, 09),
message: defaultMessage
}, {
start: minutes(12, 12),
end: minutes(12, 38),
message: lunchMessage
}, {
start: minutes(12, 42),
end: minutes(13, 31),
message: defaultMessage
}, {
start: minutes(13, 35),
end: minutes(14, 25),
message: defaultMessage
}, ];
function myFunction(myTime, periods) {
periods.every(function(period, i) {
if (myTime < period.start) {
if (i == 0) {
document.getElementById("result").innerHTML = "School has not started yet";
} else {
var timeLeft = period.start - myTime;
document.getElementById("result").innerHTML = "There are " + timeLeft + " minutes left until period " + (i+1) + " starts.";
}
} else if (myTime < period.end) {
var timeLeft = period.end - myTime;
period.message(timeLeft, i);
} else if (i == periods.length - 1) {
document.getElementById("result").innerHTML = "School has finished for today";
} else {
return true; // keep looking for the right period
}
});
}
body,
html {
height: 100%;
}
body {
background-color: #a00000;
margin: 0;
/* remove default margins added by browsers */
}
.wrapper {
display: flex;
height: 100%;
}
#result {
margin: auto;
padding: 25px;
font-weight: bold;
text-align: center;
color: black;
width: 250px;
border-radius: 10px;
background-color: white;
}
h1 {
font-weight: bold;
margin: auto;
font-size: 20px;
}
.lunch {
width: 95px;
background-color: #a00000;
color: white;
border: 1px solid black;
border-radius: 5px;
padding: 5px;
margin-top: 10px;
}
<body onload="myFunction(myTime, periods);">
<div class="wrapper">
<div id="result"></div>
</div>
</body>
I can only image how many students will be wanting to know how much time they have left ;)
What I believe you're looking for with regards to the exclusion is:
if (myTime > periods[4].start && myTime < periods[4].end) {
console.log('Lunch period');
document.getElementById("result").innerHTML = "Lunch period";
}
Place that just before if (myTime < period.start), and turn that line to an else if.
Not sure where your lunch break is from your array structure, but replace 4 with the break :)

JavaScript Amount Of Time

I'm currently working on a project that will display the amount of time left in a certain time period based on the users current time. Here is the code.
var periods = [
[ '07:45' , '08:34' ],
[ '08:38' , '09:30' ],
[ '09:34' , '10:23' ],
[ '10:27' , '11:16' ],
[ '11:20' , '12:38' ],
[ '12:42' , '15:55' ],
[ '07:00' , ]
];
updateTimePeriods();
setInterval(updateTimePeriods, 1000); // Update every second
function updateTimePeriods() {
var listEl = document.getElementById('periods');
var now = new Date();
var count = periods.length;
listEl.innerHTML='';
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
}
}
}
function duration(start, end) {
var startTime = parseTime(start);
var endTime = parseTime(end);
return endTime.getTime() - startTime.getTime();
}
function timeLeft(now, end) {
var nowTime = parseTime(formatTime(now));
var endTime = parseTime(end);
return endTime.getTime() - nowTime.getTime();
}
function parseTime(timeStr) {
var tokens = timeStr.split(':');
return new Date(1970, 0, 1, parseInt(tokens[0], 10), parseInt(tokens[1], 10));
}
function formatUTCTime(time) {
var date = new Date(time);
return padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes());
}
function formatTime(time) {
var date = new Date(time);
return padZero(date.getHours()) + ':' + padZero(date.getMinutes());
}
function formatTimeRemaining(time) {
var sign = '+';
if (time < 0) { time *= -1; sign = '–'; }
var date = new Date(time);
return sign + padZero(date.getUTCHours()) + ':' + padZero(date.getUTCMinutes()) + ':' + padZero(date.getUTCSeconds());
}
function padZero(n) { return ('00' + n).substr(-2); }
body {
background-color: #A00000;
background-size: cover;
margin: 0;
padding: 0;
}
.outer-box {
border: 3px solid black;
height: true;
width: 75%;
padding: 10px;
margin: 10px auto 10px auto;
border-radius: 10px;
background-color: white;
text-align:center;
}
#periods {
border-radius: 5px;
margin: 20px auto 20px auto;
padding: 5px;
font-weight: bold;
text-align: center;
list-style-type: none;
}
<div class="outer-box">
<ul id="periods"></ul>
</div>
My goal is only display to the user the amount of time left in the current time period instead of all of them. And if its in between a time period it shows the amount of time until the next one occurs. The issue is once all the times occur I need to tell him much time until the start of the next time which occurs on a different day. To elaborate, currently if all the time periods occur it displays a blank space because there is nothing to display and all the times are negative. I want to display the amount of time until the next days starting time.
You should break the for loop as you create the new LI element. This way it should only show the actual time period.
for (var i = 0; i < count; i++) {
if(formatTimeRemaining(timeLeft(now, periods[i][1])).charAt(0)!='–') {
child=listEl.appendChild(document.createElement('LI'));
child.innerHTML = periods[i][0] + ' — ' + periods[i][1]
+ ' => Duration: ' + formatUTCTime(duration(periods[i][0], periods[i][1]))
+ ', Remaining: ' + formatTimeRemaining(timeLeft(now, periods[i][1]));
break;
}
}

Categories

Resources