Functions In An Array & in addition, Using Time Intervals If Possible - javascript

To Summarize, I am trying to build a game that runs through questions with a timer, but not through a single timer, having each question go for 10 seconds and then reset when the 10 seconds are up. I'm very new to JavaScript so I am completely open to any advice. But I am trying to set these functions within an array and I keep getting an error saying that the function within the array doesn't exist, but it does and i've seen it work before. Am I applying the method wrong? and am I misusing the timer function?
$(document).ready(function(){
var arrayOfQuestions = [
intro(),
question1()
]
var time = 100;
function intro(){
$("#questions").html('<h6>Welcome, In this game, You will be presented with a small portion of a song and your goal is to guess the next couple of lyrics. Good Luck</h6>');
}
function question1(){
console.log("Question 1");
$("#questions").html('<h2>"Do You Remeber? The..."</h2>');
var ans1 = $("#pot-ans-1").html("<p>21st Night of September...</p>");
var ans2 = $("#pot-ans-2").html("<p>The Way...</p>");
var ans3 = $("#pot-ans-3").html("<p>How the stars stole the night away...</p>");
var ans4 = $("#pot-ans-4").html("<p>My thoughts are with you...</p>");
};
function timer() {
setTimeout(function() {
time--; //its a countdown so we are looking for decerements specifically
var secs = Math.floor(time/10);
var tenths = time % 10;
document.getElementById("timer").innerHTML = secs + ":" + tenths;
timer();
if(secs === -1) {
time = 100;
$("#timer").html("");
alert("Next Question");
};
},100);
}
$(document).ready(function(){
timer();
for (i = 0; i < arrayOfQuestions.length; i++) {
arrayOfQuestions[i]();
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Louis Pierre Questionaire</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
crossorigin="anonymous">
<link rel="stylesheet" type="text/css" media="screen" href="assets/css/style.css" />
</head>
<body>
<div id="container">
<div class="row">
<div class="col-md-12">
<center><ins>
<h1 class="Top">Welcome To Pernell's Trivia!</h1>
</ins></center>
</div>
</div>
<div class="row">
<div class="col-md-12">
<center>
<h1 class="under">Complete the song phrase!</h1>
</center>
</div>
</div>
<!-- <p class="empty space"></p> -->
<div class="ratio-c-w">
<center>
<p class="Correct"></p>
<p class="Wrong"></p>
</center>
</div>
<div class="row">
<div class="col-md-2">
</div>
<div class="col-md-8">
<center>
<p class="timer" id="timer"></p>
</center>
</div>
<div class="col-md-2">
</div>
</div>
<div class="qContainer"> <!--contains both the question and the buttons in an entire div-->
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8" id="questions-div">
<center>
<div id="questions" class="question"></div>
</center>
</div>
<div class="col-md-2"></div>
</div>
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<center>
<div id="buttons">
<button id="pot-ans-1" type="button" class="btn btn-secondary"></button>
<button id="pot-ans-2" type="button" class="btn btn-secondary"></button>
<button id="pot-ans-3" type="button" class="btn btn-secondary"></button>
<button id="pot-ans-4" type="button" class="btn btn-secondary"></button>
</div>
</center>
</div>
<div class="col-md-2"></div>
</div>
</div>
</div>
<!-- Scripts -->
<div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
crossorigin="anonymous"></script>
<script src="assets/javascript/app.js"></script>
</div>
</body>
</html>

I suggest you to:
remove the "()" statement at the end of the function call during the navigation loop of the array in order to have this arrayOfQuestions[i];, I think that the index element you are calling it's already a function and it doesn't need another "()" (I tested it here on JSFiddle and it seems to work)
modify the second argument of setTimeout() in 1000 instead of 100 since it expresses milliseconds and I grant you'll have a real 10 seconds timeout (;
Have a nice coding (;

Related

Is my html code for a canvas in a div correct?

I'm trying to put a canvas in a div so I can hide it and show it with a button and be able to resize it, but currently it isn't showing up... which is weird. Is my code correct?
<div id="blob"></div>
<script src="sketch.js"></script>
<script src="blob.js"></script>
</div>
^ it's this part of the code, the other parts are unrelated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<script defer src="script.js"></script>
<title>Quiz App</title>
</head>
<body>
</div>
<div class="container">
<div class="container2">
<img name="slide">
</div>
<div id="question-container" class="hide">
<div id="question">Question</div>
<div id="answer-buttons" class="btn-grid">
<button class="btn">Answer 1</button>
<button class="btn">Answer 2</button>
<button class="btn">Answer 3</button>
<button class="btn">Answer 4</button>
</div>
</div>
<div class="container1">
<div id="startmsgcontainer" class="hide"></div>
<div id="startmsg">Adventure Into The Human Immune System</div>
</div>
<div class="controls">
<button id="start-btn" class="start-btn btn">Start!</button>
<button id="next-btn" class="next-btn btn hide">Next</button>
<button id="end-btn" class="end-btn btn hide">End (this will close the current tab)</button>
<button id="try-btn" class="try-btn btn hide">Try again!</button>
</div>
</div>
<div class="wrapper">
<img src="img/uni.png" alt="image">
</div>
</div>
<div id="blob"></div>
<script src="sketch.js"></script>
<script src="blob.js"></script>
</div>
<div id="particles-js"></div>
<script src="particles.js"></script>
<script src="app.js"></script>
<script src="slide.js"></script>
</body>
</html>
here's how the canvas is created... I think it's correct? It worked by itself but I'm not so sure with the other things. this is sketch.js
var blob;
var blobs = [];
var zoom = 1;
function setup() {
createCanvas(600, 600);
blob = new Blob(0, 0, 64);
for (var i = 0; i < 200; i++) {
var x = random(-width, width);
var y = random(-height, height);
blobs[i] = new Blob(x, y, 16);
}
}
function draw() {
background(0);
translate(width / 2, height / 2);
var newzoom = 64 / blob.r;
zoom = lerp(zoom, newzoom, 0.1);
scale(zoom);
translate(-blob.pos.x, -blob.pos.y);
for (var i = blobs.length - 1; i >= 0; i--) {
blobs[i].show();
if (blob.eats(blobs[i])) {
blobs.splice(i, 1);
}
}
blob.show();
blob.update();
}
<script src="sketch.js"></script>
this only imports a javascript file. Unless that javascript creates a canvas element and you run it then nothing will show up

Why is my html only loading one of my two javascript scripts?

The issue I am experiencing is a frustrating one. I have tried both in my localhost and codepen to fix this but I can not figure out the issue. Essentially I have two Javascript, one runs a news feed, and one is meant to run a ticker-tape for the DOW. However, they will not run simultaneously. Any help would be greatly appreciated.
Note: This is all built on a bootstrap CSS.
<head>
<meta charset="utf-8" content="width=device-width initial-scale=1">
<title>Predictive Trades</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<link rel="stylesheet" href="{% static 'css/fixed.css' %}">
<link rel="stylesheet" href="{% static 'css/bootstrap.css' %}">
</head>
<body>
<!--- Start Landing Page Section --->
<div class="landing">
<div class="home-wrap">
<div class="home-inner">
</div>
</div>
</div>
<div class="caption text-center">
<h1>Advanced Market Analytics</h1>
<h3>Enter Company Below to get Started</h3>
<div class="container h-100">
<div class="d-flex justify-content-center h-100">
<div class="searchbar">
<input class="search_input" type="text" name="" placeholder="Search...">
<i class="fas fa-search"></i>
</div>
</div>
</div>
</div>
<div intrinio-widget-type="ticker_tape" intrinio-widget-tickers="DOW30">
<script>
(function(f,i,n,t,e,c,h){f['IntrinioWidgetsObject']=e;f[e]=f[e]||function(){
(f[e].q=f[e].q||[]).push(arguments)},f[e].l=1*new Date();c=i.createElement(n),
h=i.getElementsByTagName(n)[0];c.async=1;c.src=t;h.parentNode.insertBefore(c,h)
})(window,document,'script','https://widget-api-cdn.intrinio.com/intrinio-widgets.min.js','iw');
iw('initialize', {userId: '2095ee9f024bec258d15150a90bbe843bdd1271613906cd7b5125229f23d654b'})
</script>
</div>
<!--- End Landing Page Section --->
</div>
<!--- End Home Section --->
<!--- Start Market Section --->
<div id="market" class="offset">
<div class="col-12">
<h1 class="heading">Today's Highlights</h1>
</div>
<div class="jumbotron">
<div class="narrow">
</div>
</div>
</div><!--- End narrow --->
</div><!--- End jumbotron --->
<div id=news class="text-white-50">
<script>
window.onload= function() {
news();
}
function news() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("news").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://cloud.iexapis.com/stable/stock/spy/news/last/5?token=tpk_6925213461cb489b8c04a632e18c25dd", false);
xhttp.send();
}
</script>
</div>
</div><!--- End Market Section --->
<script type="text/javascript" src="js/news.js"></script>
<script src="js/jquery-3.4.1.min.js"></script>
<script src='js/bootstrap.js'></script>
<script src="https://use.fontawesome.com/releases/v5.5.0/js/all.js"></script>
<!--- End Script Source Files --->
</body>
Use this to load your news. You where using window.onload and I guessed your other function was preventing the window to be loaded fully, this way its fired soon as dom is ready.
<div id=news class="text-white-50">
<script>
document.onreadystatechange = function(e)
{
if (document.readyState === 'complete')
{
news();
}
};
</script>
</div>
You can find more info here:
How to execute code before window.load and after DOM has been loaded?

How do I make this loop print the values I need?

I'm rather new to Javascript, so please excuse simple mistakes if I made any. I need to make a task board page. The user inputs a value (a task and a date) and JS saves it into an object. The object is pushed into an array and saved to Local Storage. After that, it fades in a note (did this with an image and CSS effects) and prints the value on top of it. To accomplish this I tried using a For loop to go through the array when I get it back from local storage, but it only keeps printing the first value the user entered.
This is my code:
var taskArray = [];
var imgs = document.getElementsByTagName("img");
$(document).ready(function hideImages() {
$("img").hide();
})
function saveToLocalStorage() {
//debugger;
var taskName = document.getElementById("task").value;
var taskDate = document.getElementById("date").value;
var task = {
name: taskName,
date: taskDate
}
taskArray.push(task);
var arrayToString = JSON.stringify(taskArray);
localStorage.setItem("user tasks", arrayToString);
var mainDiv = document.getElementById("maindiv");
var arrayFromStorage = localStorage.getItem('user tasks');
arrayFromStorage = JSON.parse(arrayFromStorage);
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML += `
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[x].name}
Complete by = ${arrayFromStorage[x].date}
</span>
`
x++
addText();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<title></title>
</head>
<body class="background-image">
<h1 class="pageheader">My Task Board</h1>
<form class="" action="index.html" method="post">
<div class="container">
<div class="row">
<input type="text" class="form-control col-sm centerInput" id="task" placeholder="Enter a Task">
<input type="date" class="form-control col-sm centerInput" id="date" value="">
</div>
<div class="form-group">
<input type="button" class="form-control btn btn-success" id="submit" value="Submit Task" onclick="saveToLocalStorage()">
</div>
<div class="form-group">
<input type="reset" class="form-control btn btn-success " id="reset" value="Reset Form">
</div>
</div>
</form>
<div class="imgContainer" id="maindiv">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<!-- load the script at the end of body tag -->
</body>
</html>
Any help would be greatly appreciated, cheers!
Try putting index instead of x in your loop.
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML +=
`
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[index].name}
Complete by = ${arrayFromStorage[index].date}
</span>
`
}

Add and remove rows in a form with unique id's that returns an object as an array

I already have my own solution for this problem, but then I don't know if I'm using the best techniques/practices to solve this particular scenario, which involves removing and adding DOM elements with unique id's.
I have just used jQuery, the requirements where only a button to add any amount of rows, once another row is added be able to delete that row too, the first row is always mandatory, here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <title>Simple form</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<style type="text/css">
label{
display: block;
}
</style>
</head>
<body>
<div class="container">
<div class="row inputRows">
<div class="col-sm-12" id="newRow-1">
<label>Some label over input</label>
<input type="text" name="txt">
</div>
</div>
<div class="row">
<div class="col-sm-12">
<button id="addRow"><span class="fa fa-plus"></span> Add </button>
<button id="viewInfo"><span class="fa fa-plus"></span> Info </button>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p id="result">
</p>
</div>
</div>
</div>
<script src="https://npmcdn.com/tether#1.2.4/dist/js/tether.min.js"></script>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
<script type="text/javascript">
$('.inputRows').on('click', 'button' ,function(){
$(this).parent().remove();
});
$('#addRow').click(function(){
var $newRow = $('div[id^="newRow"]:first').clone(),
newId = Number($('div[id^="newRow"]:last').attr('id').split('-')[1]) + 1;
$newRow.append('<button><span class="fa fa-trash-o"></span></button>');
$newRow.find('input').val('');
$newRow.attr('id','newRow-' + newId);
$('.inputRows').append($newRow);
});
$('#viewInfo').click(function(){
$('#result').text(JSON.stringify(objectifyForm($('div[id^="newRow"]'))));
});
function objectifyForm(formArray) {
var resultArray = {},
inputValue = '';
for (var i = 0; i < formArray.length; i++){
inputValue = $(formArray[i]).find('input').val();
if(inputValue){
resultArray[$(formArray[i]).attr('id')] = inputValue;
}
}
return resultArray;
}
</script>
</body>
</html>
So the code works, the only problem I see is that the numeration of the id's, can sometimes be 1,5,8,7,6,12 depending on which ones you delete, but then it's fine because in the end, it doesn't even matter (joke, RIP Chester, but kind of true). My main concern or question is, is there any other way of achieving this more efficiently using jQuery? Am I doing something wrong by cloning the first element multiple times? If you can share some knowledge on DOM manipulation that would be great.
Thanks in advance,
Leo.

Countdown script not starting countdown

Can someone please tell me why the countdown function is not working properly (the countdown is not starting in the div with the I.D. "countdown"). Probably something real simple, but Javascript isn't my forte. This is the countdown plugin I am using: http://keith-wood.name/countdown.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Page Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="./css/web-style-second.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="chrome://mozbar/skin/css/injected.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.countdown.js"></script>
</head>
<body>
<a name="top"></a>
<div id="container">
<div id="content">
<div class="center">
<center>
<div></div>
</center>
</div>
<script type="text/javascript">
$(function() {
$('#countdown').countdown({
until: '14min+20sec',
format: 'MS',
layout: '{mnn}min ' + '{snn}sec ',
onExpiry: function() {
$(".hidden").css("display", "block");
}
});
});
</script>
<div class="time_box">
<h3 class="italic">When The Clock Hits Zero ... </h3>
<h4 class="hasCountdown" id="countdown">14min 20sec </h4>
</div>
<form name="signupFrm" id="signupFrm" action="#" method="post" class="hidden">
<div>
<div class="yellow_red">
<h1></h1>
</div>
<div class="center">
<a href="https://www.testing.com" class="btn_buy_now">
Get Started</a>
</div>
<input name="submit" value="submit" type="hidden">
<p class="mb_5"> </p>
</div>
</form>
<div class="fnote justify">
</div>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
You should put the $(function () ...) script into the <head> tag of your HTML page. This way, the countdown will be initiated once the DOM has fully loaded.
I think that the problem is that you are missing the reference to the "jQuery Countdown CSS". In the usage instructions of the plugin it says:
Download and include the jQuery Countdown CSS and JavaScript in the
head section of your page. #import
"jquery.countdown.css";
But you can still make it work without the "jQuery Countdown CSS" if you remove the class attribute from the <h4> element with the id "countdown", like this:
<div class="time_box">
<h3 class="italic">When The Clock Hits Zero ... </h3>
<h4 id="countdown">14min 20sec </h4>
</div>
​JSFiddle Example
The countdown plugin uses the class hasCountdown to test whether the countdown has already been instantiated, so you should use a different class name.
From jquery.countdown.js:
/* Class name added to elements to indicate already configured with countdown.*/
markerClassName: 'hasCountdown'

Categories