I have made a questionnaire that asks 10 questions, however I would like to add a small timer to show how long the user has taken in seconds. I have looked online for help however I always have some issue with displaying the timer itself.
Here's my program:
<html>
<head>
<title>Best Gaming Quiz Ever!</title>
</head>
<body>
<h1>Gaming Quiz</h1>
We have made 10 questions for you to answer about gaming and gaming companies. Do your best, and don't guess,
<br>it's really not that difficult. Also, try not to be a cheating noob and click "check answer" before you make your choice!
<br>Challenge yourself, and have fun!
<h2>Your mission:</h2>
Just pick the correct answer, duh, it's a quiz, what else?
<br>
<br>
<script type="text/javascript">
var allowPeeking = 1
var allowDoOvers = 1
questions = new Array();
// Q & A questions set as Arrays below
// Questions are used first
// Correct answer is followed with "right"
// all wrong ones with ""
questions[0] = ["Which are gaming companies?:", "Valve", "right", "Microsoft", "", "Apple", "", "FedEx", ""]
questions[1] = ["Which is a game?:", "Micrsoft Word", "", "Piskel", "", "Dota 2", "right", "csTimer.net", ""]
// To display question array list
for (i = 0; i < questions.length; i++) {
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "")
questions[i][j] = ("w" + i) + j
if (questions[i][j] == "right")
questions[i][j] = "right" + i
}
}
var ie = document.all
// diplays answer holder when button is pressed
function showAnswer(el, ans) {
ie ? ie[el].innerHTML = 'The answer is: ' + ans : document.getElementById(el).innerHTML = 'The answer is: ' + ans
}
function addup() {
var q, right, statement, total = 0
quizQuests = new Array();
for (i = 0; i < questions.length; i++)
quizQuests[i] = 0
if (document.forms.quiz.q0['right0']) {
for (i = 0; i < questions.length; i++) {
q = "q" + i
right = "right" + i
// takes away 1 if incorrect!
if (document.forms.quiz[q][right].checked)
quizQuests[i] += -1
}
} else if (document.getElementById) {
for (i = 0; i < questions.length; i++) {
right = "right" + i
// adds 2 if correct!
if (document.getElementById(right).checked)
quizQuests[i] = 2
}
} else
return;
for (i = 0; i < questions.length; i++)
total += quizQuests[i]
// Displays end score (Attempted to get percentage but remove as it wouldn't calculate correctly)
statement = 'You scored ' + total + ' points out of 20'
ie ? ie.results.innerHTML = statement : document.getElementById('results').innerHTML = statement
}
function clearR() {
ie ? ie.results.innerHTML = '' : document.getElementById('results').innerHTML = ''
for (i = 0; i < questions.length; i++)
if (allowPeeking)
ie ? ie["ans" + i].innerHTML = '' : document.getElementById("ans" + i).innerHTML = ''
window.scrollTo(0, 0);
}
document.write('<hr><form name="quiz">')
var correct, answersString
// displaying answers & checking correct / wrong choices
for (i = 0; i < questions.length; i++) {
answersString = ''
for (k = 1; k < questions[i].length; k += 2)
answersString += '<input id="' + questions[i][(k + 1)] + '" type="radio" unchecked name="q' + i + '"><label for="' + questions[i][(k + 1)] + '">' + questions[i][k] + '</label><br>'
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "right" + i)
correct = questions[i][j - 1]
}
with(document) {
write('Question ' + (i + 1) + ':<br><br>')
write(questions[i][0] + '<br>')
write(answersString)
// simply displays answer ("right" - 1)
if (allowPeeking)
write('<input class="chkans" type="button" value="Check Answer" onclick="showAnswer(\'ans' + i + '\',\'' + correct + '\')"> <span id="ans' + i + '" class="chkans"></span><br> ')
write('<br>')
}
}
with(document) {
// calls addup function
write('<hr><br>')
write('<input type="button" value="See Score" onclick="addup()"> <span id="results"></span><br> <br>')
// calls clearR function
if (allowDoOvers)
write('<input type="button" value="Start Again" onclick="reset();clearR()">')
write('</form>')
}
</script>
</body>
</html>
Appreciate any help given.
Check below answer. The timer will stop when you click the button See Score.
<html>
<head>
<title>Best Gaming Quiz Ever!</title>
</head>
<body>
<h1>Gaming Quiz</h1>
We have made 10 questions for you to answer about gaming and gaming companies. Do your best, and don't guess,
<br>it's really not that difficult. Also, try not to be a cheating noob and click "check answer" before you make your choice!
<br>Challenge yourself, and have fun!
<h2>Your mission:</h2>
Just pick the correct answer, duh, it's a quiz, what else?
<br>
<br>
<hr>
<br>
<b>Time taken:</b> <span id="timer">0</span> seconds
<br>
<br>
<script type="text/javascript">
var t = 0;
var runTimer = setInterval(function() {
t++;
document.getElementById("timer").innerHTML = t;
}, 1000);
var allowPeeking = 1
var allowDoOvers = 1
questions = new Array();
// Q & A questions set as Arrays below
// Questions are used first
// Correct answer is followed with "right"
// all wrong ones with ""
questions[0] = ["Which are gaming companies?:", "Valve", "right", "Microsoft", "", "Apple", "", "FedEx", ""]
questions[1] = ["Which is a game?:", "Micrsoft Word", "", "Piskel", "", "Dota 2", "right", "csTimer.net", ""]
// To display question array list
for (i = 0; i < questions.length; i++) {
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "")
questions[i][j] = ("w" + i) + j
if (questions[i][j] == "right")
questions[i][j] = "right" + i
}
}
var ie = document.all
// diplays answer holder when button is pressed
function showAnswer(el, ans) {
ie ? ie[el].innerHTML = 'The answer is: ' + ans : document.getElementById(el).innerHTML = 'The answer is: ' + ans
}
function addup() {
clearInterval(runTimer);
var q, right, statement, total = 0
quizQuests = new Array();
for (i = 0; i < questions.length; i++)
quizQuests[i] = 0
if (document.forms.quiz.q0['right0']) {
for (i = 0; i < questions.length; i++) {
q = "q" + i
right = "right" + i
// takes away 1 if incorrect!
if (document.forms.quiz[q][right].checked)
quizQuests[i] += -1
}
} else if (document.getElementById) {
for (i = 0; i < questions.length; i++) {
right = "right" + i
// adds 2 if correct!
if (document.getElementById(right).checked)
quizQuests[i] = 2
}
} else
return;
for (i = 0; i < questions.length; i++)
total += quizQuests[i]
// Displays end score (Attempted to get percentage but remove as it wouldn't calculate correctly)
statement = 'You scored ' + total + ' points out of 20'
ie ? ie.results.innerHTML = statement : document.getElementById('results').innerHTML = statement
}
function clearR() {
ie ? ie.results.innerHTML = '' : document.getElementById('results').innerHTML = ''
for (i = 0; i < questions.length; i++)
if (allowPeeking)
ie ? ie["ans" + i].innerHTML = '' : document.getElementById("ans" + i).innerHTML = ''
window.scrollTo(0, 0);
}
document.write('<hr><form name="quiz">')
var correct, answersString
// displaying answers & checking correct / wrong choices
for (i = 0; i < questions.length; i++) {
answersString = ''
for (k = 1; k < questions[i].length; k += 2)
answersString += '<input id="' + questions[i][(k + 1)] + '" type="radio" unchecked name="q' + i + '"><label for="' + questions[i][(k + 1)] + '">' + questions[i][k] + '</label><br>'
for (j = 0; j < questions[i].length; j++) {
if (questions[i][j] == "right" + i)
correct = questions[i][j - 1]
}
with(document) {
write('Question ' + (i + 1) + ':<br><br>')
write(questions[i][0] + '<br>')
write(answersString)
// simply displays answer ("right" - 1)
if (allowPeeking)
write('<input class="chkans" type="button" value="Check Answer" onclick="showAnswer(\'ans' + i + '\',\'' + correct + '\')"> <span id="ans' + i + '" class="chkans"></span><br> ')
write('<br>')
}
}
with(document) {
// calls addup function
write('<hr><br>')
write('<input type="button" value="See Score" onclick="addup()"> <span id="results"></span><br> <br>')
// calls clearR function
if (allowDoOvers)
write('<input type="button" value="Start Again" onclick="reset();clearR()">')
write('</form>')
}
</script>
</body>
</html>
Related
As I am new to JavaScript, I am a bit confused of using the for loops in JavaScript. I have tried the times table using the below JavaScript code, but I was unsuccessful in creating the times table for 1 to 9, as displayed in the image.
var display = ""; // The table output HTML
for (i = 1; i <= 9; i++) {
var multiplier = 1;
var result = i * 1;
display += multiplier + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
document.getElementById("outputDiv").innerHTML = display;
I tried using nested for loops, but it left me with an error
This is where I have done with a single for loop
https://codepen.io/vbudithi/pen/LgEPwx
I tried to get the output in the below form
THANKS IN ADVANCE
Use nested loop with break line. "< br >"
Working example: https://codepen.io/anon/pen/yRyLje
var display = "";
for( i = 1; i < 10; i++){
for (j = i; j < 10; j++) {
display += i + " * " + j + " = " + j * i+ "\xa0\xa0\xa0\xa0\xa0" ;
}
display +="<br>";
}
document.getElementById("outputDiv").innerHTML = display;
just like NicolasB said, wrapping the loop in another loop
var display = ""; // The table output HTML
for(j = 1; j <= 9; j++) {
for (i = j; i <= 9; i++) {
var result = i * j;
display += j + " * " + i + " = " + result + "\xa0\xa0\xa0\xa0\xa0\xa0\xa0 " ;
}
display += "<br>";
}
document.getElementById("outputDiv").innerHTML = display;
I am using the script below to show the latest 5 posts on my Blogger blog. How can I wrap the first and last 2 posts in different div containers? Currently all the 5 posts are inside a wrapper container stored in the item variable:
<script type='text/javascript'>
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
document.write(item);
}
}
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>
More generic solution would not check for last and previous to last elements checking for 3 or 4 but should be based on total length of your posts (it can be 3 it can be 10000).
Checks below should be place in your loop.
if(i === 0 || i === 1)
Always use === operator as it is typesafe.
Also group your checks in a way that is easy to understand (check for first and second in one if and for last and previous to last in another if:
if(i === json.feed.entry.length || i === json.feed.entry.length - 1) - this check is based on length of your entries, not some fixed value like 3 or 4.
This way if your displayed entries value will change in future (to ex. 10), you don't need to adjust your code here. All code you write should strive to work without such adjustments when code it uses changes.
Check desired elements through loop
// to check first or fourth element
if (i == 0 || i == 3)
// to check second or fifth element
if (i == 1 || i == 4)
Wrap them by adding HTML tages
<script type='text/javascript'>
function mycallback(json) {
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
var postTitle = json.feed.entry[i].title.$t;
var postAuthor = json.feed.entry[i].author[0].name.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0,400);
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postImage = json.feed.entry[i].media$thumbnail.url.replace('s72-c/','s1600/');
var item = '<div class="wrapper"><img src="' + postImage + '"/><h3><a href=' + postUrl + '>' + postTitle + '</h3></a><span>'+ postAuthor + '</span><p>' + postContent + '</p></div>';
if (i == 0 || i == 3) document.write('<div>');
document.write(item);
if (i == 1 || i == 4) document.write('</div>');
}
}
</script>
<script src="/feeds/posts/summary?orderby=published&max-results=5&alt=json-in-script&callback=mycallback"></script>
for example my toGuess number is 50 and my best lower guess is 48 but I guess 47 and it changes my best lower guess to that 47.
What I mean by this is that I want it not go lower anymore
Same thing with the higher guess
I want it to save/lock my best guess to the closest
'use strict'
var toGuess = Math.floor(Math.random() * (100 + 1));
console.log("To Guess: " + toGuess);
var guess = undefined;
var amount = 0;
var bestHigher = 100;
var bestLower = 0;
var hint = document.getElementById('hint');
var numbers = document.getElementById('numbers');
var lower = document.getElementById('lower');
var higher = document.getElementById('higher');
function GuessDone() {
var put = document.getElementById('number').value;
guess = Number(put);
console.log("Guess: " + guess);
document.getElementById('form').reset();
amount = amount + 1;
console.log("Guesses " + amount);
var numberDif = Number(toGuess) - Number(put);
var bestLower = Number(put) > toGuess;
var bestHigher = Number(put) < toGuess;
if (numberDif > bestLower) {
bestLower = Number(put);
console.log("Lower " + bestLower);
}
if (numberDif < bestHigher) {
bestHigher = Number(put);
console.log("Higher " + bestHigher);
}
if (guess > toGuess) {
hint.innerHTML = "You need to guess lower";
higher.innerHTML = "Best guess above " + bestHigher;
} else if (guess < toGuess) {
hint.innerHTML = "You need to guess higher";
lower.innerHTML = "Best guess below " + bestLower;
} else {
hint.innerHTML = "Congratz, " + toGuess + " was right! Guesses " + amount;
var print = "";
var i;
for (i = 0; i <= toGuess; i++) {
print += i + "<br>";
}
numbers.innerHTML = print;
}
return false;
EDIT
This is my html
<form id="form">
<label for="number">Guess number between 0-100: </label>
<input id="number" type="text" name="number">
<button type="submit">Guess</button>
</form>
<p id="lower"></p>
<p id="higher"></p>
<p id="hint"></p>
<p id="numbers"></p>
<script src="numbergame.js"></script>
FIDDLE
https://jsfiddle.net/d3761nbj/2/
I am new to jQuery and I cant seem to get the following code working..
for ( var i = 0; i < 2; i++ ) {
$status[i] = $('select[name="status'+ i +'"] option:selected').val();
$odd_a[i] = $("input:text[name='odd_a"+ 1 +"']").val();
$odd_b[i] = $("input:text[name='odd_b"+ 1 +"']").val();
$term[i] = $("select[name='term"+ 1 +"'] option:selected").val();
$dh_place[i] = $("input:text[name='dh_place"+ 1 +"']").val();
$dh_total[i] = $("input:text[name='dh_total"+ 1 +"']").val();
}
I have several text boxes "status1, status2, status3 etc. I need to call their name by the for loop. If I replace the "i" with the "1" it works. I cant seem to call the variable "i" at that position.
Try with
$status[i] = $('select[name="status'+ i +'"]').val();
and You need to start i value from 1 like
for ( var i = 1; i < 2; i++ ) {
One problem I can see is the i starts with 0 where as your input starts with 1, so the first loop will not return any elements.
for (var i = 0; i < 2; i++) {
$status[i] = $('select[name="status' + (i + 1) + '"]').val();
$odd_a[i] = $("input:text[name='odd_a" + (i + 1) + "']").val();
$odd_b[i] = $("input:text[name='odd_b" + (i + 1) + "']").val();
$term[i] = $("select[name='term" + (i + 1) + "']").val();
$dh_place[i] = $("input:text[name='dh_place" + (i + 1) + "']").val();
$dh_total[i] = $("input:text[name='dh_total" + (i + 1) + "']").val();
}
Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?