Javascript not adding questions or buttons to webpage - javascript

I am trying to make a quiz website and I used some simple interactive quiz code and the next button is there (only button I have that doesn't have display set to none). The Javascript was supposed to show the first question upon opening the page, and then showing the next one each time you hit next. After the first question the previous button should show up and at the end it would give you your score and the start over button.
Html:
<!DOCTYPE html>
<html>
<head>
<title>History</title>
<link rel="stylesheet" type="text/css" href="../css.css">
<script src="javascript.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src='javascript.js'></script>
</head>
<div id="background">
<div id="headnav">
<h1 class="navitem">World Wide Water</h1> <!-- Going to be the header with navigatioon bar-->
<ul id="nav">
<li class="navitem">Home</li>
<li class="navitem">About</li>
<li class="navitem">Subjects</li>
<li class="navitem">Share</li>
<li class="navitem">Donate More!</li>
</ul>
<div id="header">
<div id="headerbar">
<div id="logo"></div>
<div id="site-sloagan"></div>
</div>
</div>
</div>
<div id="mainhis">
<p>If i do this will it work</p>
<div id="quiz"></div>
<div class='button' id='next'><a href='#'>Next</a></div>
<div class='button' id='prev'><a href='#'>Previous</a></div>
<div class='button' id='start'><a href='#'>Start Over</a></div>
</div>
</div></html>
CSS:
body {
background-image: url("bg.jpeg");
background-repeat: no-repeat;
}
#headnav {
background-color: rgb(0, 0, 153);
color: white;
}
#main {
background-color: white;
text-align: left;
min-width: 900px;
max-width: 900px;
}
#nav {
list-style-type: none;
margin: 0;
padding: 0;
float: center;
}
.navitem {
display: inline;
color: white;
}
.linkonsub {
color: black;
}
#id {
text-align: left;
}
#sub {
background-color: rgb(211, 112, 40);
text-align: left;
}
#mainhis {
width:50%;
margin:auto;
padding: 0 25px 40px 10px;
background-color: #1E90FF;
border:4px solid #B0E0E6;
border-radius:5px;
color: #FFFFFF;
font-weight: bold;
box-shadow: 5px 5px 5px
#888;
}
#quiz {
text-indent: 10px;
display:none;
}
.button {
border:4px solid;
border-radius:5px;
width: 40px;
padding-left:5px;
padding-right: 5px;
position: relative;
float:right;
background-color: #DCDCDC;
color: black;
margin: 0 2px 0 2px;
}
.button.active {
background-color: #F8F8FF
color: #525252;
}
button {
position: relative;
float: right;
}
.button a {
text-decoration: none;
color: black;
}
ul {
list-style-type: none;
padding: 0;
margin: 0;
}
#prev {
display: none;
}
#start {
display: none;
width: 90px;
}
Javascript:
(function() {
var questions = [{
question: "What is 2*5?",
choices: [2, 5, 10, 15, 20],
correctAnswer: 2
}, {
question: "What is 3*6?",
choices: [3, 6, 9, 12, 18],
correctAnswer: 4
}, {
question: "What is 8*9?",
choices: [72, 99, 108, 134, 156],
correctAnswer: 0
}, {
question: "What is 1*7?",
choices: [4, 5, 6, 7, 8],
correctAnswer: 3
}, {
question: "What is 8*8?",
choices: [20, 30, 40, 50, 64],
correctAnswer: 4
}];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<h2>Question ' + (index + 1) + ':</h2>');
qElement.append(header);
var question = $('<p>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();

The issue is very simple. You're missing the $ at the very start of the Javascript code. Add that in and you're golden. To explain, you can use the dollar sign as a function name. jQuery (which you're using) does this to make it very quick and easy to type. When you use $ all by itself, it takes a function as an argument (i.e. you pass in a callback function) and that callback function is called as soon as the page is loaded. That's nothing special or magical, it's just what the $() function does, and it's part of jQuery. People use it because the callback function is called when the page is ready to be manipulated; that is, it's called when all the HTML has been generated, which means it's safe for the Javascript to start messing around with it.
So your code was just running before the page was ready.
Fix like so:
$(function() {
var questions = [{
question: "What is 2*5?",
choices: [2, 5, 10, 15, 20],
correctAnswer: 2
}, {
question: "What is 3*6?",
choices: [3, 6, 9, 12, 18],
correctAnswer: 4
}, {
question: "What is 8*9?",
choices: [72, 99, 108, 134, 156],
correctAnswer: 0
}, {
question: "What is 1*7?",
choices: [4, 5, 6, 7, 8],
correctAnswer: 3
}, {
question: "What is 8*8?",
choices: [20, 30, 40, 50, 64],
correctAnswer: 4
}];
var questionCounter = 0; //Tracks question number
var selections = []; //Array containing user choices
var quiz = $('#quiz'); //Quiz div object
// Display initial question
displayNext();
// Click handler for the 'next' button
$('#next').on('click', function (e) {
e.preventDefault();
// Suspend click listener during fade animation
if(quiz.is(':animated')) {
return false;
}
choose();
// If no user selection, progress is stopped
if (isNaN(selections[questionCounter])) {
alert('Please make a selection!');
} else {
questionCounter++;
displayNext();
}
});
// Click handler for the 'prev' button
$('#prev').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
choose();
questionCounter--;
displayNext();
});
// Click handler for the 'Start Over' button
$('#start').on('click', function (e) {
e.preventDefault();
if(quiz.is(':animated')) {
return false;
}
questionCounter = 0;
selections = [];
displayNext();
$('#start').hide();
});
// Animates buttons on hover
$('.button').on('mouseenter', function () {
$(this).addClass('active');
});
$('.button').on('mouseleave', function () {
$(this).removeClass('active');
});
// Creates and returns the div that contains the questions and
// the answer selections
function createQuestionElement(index) {
var qElement = $('<div>', {
id: 'question'
});
var header = $('<h2>Question ' + (index + 1) + ':</h2>');
qElement.append(header);
var question = $('<p>').append(questions[index].question);
qElement.append(question);
var radioButtons = createRadios(index);
qElement.append(radioButtons);
return qElement;
}
// Creates a list of the answer choices as radio inputs
function createRadios(index) {
var radioList = $('<ul>');
var item;
var input = '';
for (var i = 0; i < questions[index].choices.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += questions[index].choices[i];
item.append(input);
radioList.append(item);
}
return radioList;
}
// Reads the user selection and pushes the value to an array
function choose() {
selections[questionCounter] = +$('input[name="answer"]:checked').val();
}
// Displays next requested element
function displayNext() {
quiz.fadeOut(function() {
$('#question').remove();
if(questionCounter < questions.length){
var nextQuestion = createQuestionElement(questionCounter);
quiz.append(nextQuestion).fadeIn();
if (!(isNaN(selections[questionCounter]))) {
$('input[value='+selections[questionCounter]+']').prop('checked', true);
}
// Controls display of 'prev' button
if(questionCounter === 1){
$('#prev').show();
} else if(questionCounter === 0){
$('#prev').hide();
$('#next').show();
}
}else {
var scoreElem = displayScore();
quiz.append(scoreElem).fadeIn();
$('#next').hide();
$('#prev').hide();
$('#start').show();
}
});
}
// Computes score and returns a paragraph element to be displayed
function displayScore() {
var score = $('<p>',{id: 'question'});
var numCorrect = 0;
for (var i = 0; i < selections.length; i++) {
if (selections[i] === questions[i].correctAnswer) {
numCorrect++;
}
}
score.append('You got ' + numCorrect + ' questions out of ' +
questions.length + ' right!!!');
return score;
}
})();
Of course your head should also look more like this:
<head>
<title>History</title>
<link rel="stylesheet" type="text/css" href="../css.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src='javascript.js'></script>
</head>

You need to replace your function "(function() {" with
"$(window).on("load", function() {"
Your Quiz div is getting loaded later on after the functions get executed and hence your first question is not getting loaded. Hope this resolves the issue.

I believe that you have two problems here and both are related to html and js loading.
you are linking your script twice (maybe copy error?) and the first time before you add reference to jQuery, so your script is failing because it is loaded before you add jQuery and since your script is self executing function it will try to run immediately after it is loaded but will fail because jQuery which it relies on is not loaded yet.
again your script will run as soon as it is loaded and not add the correct handlers, etc.. because it is actually loaded before the rest of the html code, so it can't add those handlers to elements. So your solution here is either use some body onload hook and do the init there, or put the <script type="text/javascript" src='javascript.js'></script>at the bottom of the page so when it is loaded you can be sure that rest of the HTML code is loaded as well.

Related

Show images in quiz javascript

I'm trying to create a quiz that tests users awareness of real and fake emails. What I want to do is have the question displayed at the top saying "Real or Fake", then have an image displayed underneath which the user needs to look at to decided if it's real or fake. There are two buttons, real and fake, and regardless of whether they choose the right answer I want to swap the original image with annotated version - showing how users could spot that it was fake or real.
But I'm not sure how to show the annotated version once the answer has been submitted. Could someone help?
function Quiz(questions) {
this.score = 0;
this.questions = questions;
this.questionIndex = 0;
}
Quiz.prototype.getQuestionIndex = function() {
return this.questions[this.questionIndex];
}
Quiz.prototype.guess = function(answer) {
if (this.getQuestionIndex().isCorrectAnswer(answer)) {
this.score++;
}
this.questionIndex++;
}
Quiz.prototype.isEnded = function() {
return this.questionIndex === this.questions.length;
}
function Question(text, choices, answer) {
this.text = text;
this.choices = choices;
this.answer = answer;
}
Question.prototype.isCorrectAnswer = function(choice) {
return this.answer === choice;
}
function populate() {
if (quiz.isEnded()) {
showScores();
} else {
// show question
var element = document.getElementById("question");
element.innerHTML = quiz.getQuestionIndex().text;
// show options
var choices = quiz.getQuestionIndex().choices;
for (var i = 0; i < choices.length; i++) {
var element = document.getElementById("choice" + i);
element.innerHTML = choices[i];
guess("btn" + i, choices[i]);
}
showProgress();
}
};
function guess(id, guess) {
var button = document.getElementById(id);
button.onclick = function() {
quiz.guess(guess);
populate();
}
};
function showProgress() {
var currentQuestionNumber = quiz.questionIndex + 1;
var element = document.getElementById("progress");
element.innerHTML = "Question " + currentQuestionNumber + " of " + quiz.questions.length;
};
function showScores() {
var gameOverHTML = "<h1>Result</h1>";
gameOverHTML += "<h2 id='score'> Your scores: " + quiz.score + "</h2>";
var element = document.getElementById("quiz");
element.innerHTML = gameOverHTML;
};
// create questions here
var questions = [
new Question("<img src= 'netflix_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'dropbox_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'gov_real.jpg' />", ["Real", "Fake"], "Real"),
new Question("<img src= 'paypal_fake.jpg' />", ["Real", "Fake"], "Fake"),
new Question("<img src= 'gmail.jpg' />", ["Real", "Fake"], "Fake")
];
//create quiz
var quiz = new Quiz(questions);
// display
populate();
body {
background-color: #538a70;
}
.grid {
width: 600px;
height: 500px;
margin: 0 auto;
background-color: #fff;
padding: 10px 50px 50px 50px;
border: 2px solid #cbcbcb;
}
.grid h1 {
font-family: "sans-serif";
font-size: 60px;
text-align: center;
color: #000000;
padding: 2px 0px;
}
#score {
color: #000000;
text-align: center;
font-size: 30px;
}
.grid #question {
font-family: "monospace";
font-size: 30px;
color: #000000;
}
.buttons {
margin-top: 30px;
}
#btn0,
#btn1,
#btn2,
#btn3 {
background-color: #a0a0a0;
width: 250px;
font-size: 20px;
color: #fff;
border: 1px solid #1D3C6A;
margin: 10px 40px 10px 0px;
padding: 10px 10px;
}
#btn0:hover,
#btn1:hover,
#btn2:hover,
#btn3:hover {
cursor: pointer;
background-color: #00994d;
}
#btn0:focus,
#btn1:focus,
#btn2:focus,
#btn3:focus {
outline: 0;
}
#progress {
color: #2b2b2b;
font-size: 18px;
}
<div class="grid">
<div id="quiz">
<h1>Can you spot the fake email?</h1>
<hr style="margin-bottom: 20px">
<p id="question"></p>
<div class="buttons">
<button id="btn0"><span id="choice0"></span></button>
<button id="btn1"><span id="choice1"></span></button>
</div>
<hr style="margin-top: 50px">
<footer>
<p id="progress">Question x of y</p>
</footer>
</div>
</div>
When user clicks button I trigger class and I add it second name, on second I have written to get swapped, I wrote you basically full project, and please read the whole comments, to understand logic
//Calling Elements from DOM
const button = document.querySelectorAll(".check");
const images = document.querySelectorAll(".image");
const answer = document.querySelector("h1");
//Declaring variable to randomly insert any object there to insert source in DOM Image sources
let PreparedPhotos;
//Our Images Sources and With them are its fake or not
//fake: true - yes its fake
//fake: false - no its real
const image = [
[
{
src:
"https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/1200px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg",
fake: true
},
{
src:
"http://graphics8.nytimes.com/images/2012/04/13/world/europe/mona-lisa-like-new-images/mona-lisa-like-new-images-custom4-v3.jpg",
fake: false
}
],
[
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/Creacion_de_Adan__Miguel_Angel_f5adb235-bfa8-4caa-8ffb-c5328cbad953_grande.jpg?12799626327330268216",
fake: false
},
{
src:
"https://cdn.shopify.com/s/files/1/0849/4704/files/First-image_Fb-size_grande.jpg?10773543754915177139",
fake: true
}
]
];
//Genrating Random Photo on HTML
function setRandomPhoto() {
//Random Number which will be length of our array of Object
//if you array includes 20 object it will generate random number
// 0 - 19
const randomNumber = Math.floor(Math.random() * image.length);
//Decalaring our already set variable as Array Object
PreparedPhoto = image[randomNumber];
//Our first DOM Image is Variables first object source
images[0].src = PreparedPhoto[0].src;
//and next image is next object source
images[1].src = PreparedPhoto[1].src;
}
//when windows successfully loads, up function runs
window.addEventListener("load", () => {
setRandomPhoto();
});
//buttons click
//forEach is High Order method, basically this is for Loop but when you want to
//trigger click use forEach - (e) is single button whic will be clicked
button.forEach((e) => {
e.addEventListener("click", () => {
//decalring variable before using it
let filtered;
//finding from our DOM image source if in our long array exists
//same string or not as Image.src
//if it exists filtered variable get declared with that found obect
for (let i = 0; i < image.length; i++) {
for (let k = 0; k < 2; k++) {
if (image[i][k].src === images[0].src) {
filtered = image[i][k];
}
}
}
//basic if else statement, if clicked button is Fake and image is true
//it outputs You are correct
//if clicked button is Real and Image is false it outputs Correct
//Else its false
//Our image checking comes from filtered variable
if (e.innerText === "Fake" && filtered.fake === true) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else if (e.innerText === "Real" && filtered.fake === false) {
answer.innerText = "You Are Correct";
images.forEach((image) => {
image.classList.toggle("hidden");
});
} else {
answer.innerHTML = "You are Wrong";
images.forEach((image) => {
image.classList.toggle("hidden");
});
}
});
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100%;
min-height: 100vh;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
.image-fluid {
display: flex;
}
.image-fluid .image {
width: 200px;
margin: 0 10px;
transition: 0.5s;
}
.image-fluid .image:nth-child(1).hidden {
transform: translateX(110px);
}
.image-fluid .image:nth-child(2).hidden {
transform: translateX(-110px);
}
<div class="container">
<div class="image-fluid">
<img src="" class="image hidden">
<img src="" class="image hidden">
</div>
<div class="button-fluid">
<button class="check">Fake</button>
<button class="check">Real</button>
</div>
</div>
<h1></h1>

How to prevent centered text in input button be moved when dynamically changed

I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button.
Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text.
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
var dot = '.';
if(dots < 3) {
$('#payDots').val('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').val('processing');
dots = 0;
}
}
<input id="payDots" type="button" value="Pay" class="button">
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
https://jsfiddle.net/v8g4rfsw/1/ (button should be pressed)
The easiest as this is a value and extra elements can't be inserted, would be to just use leading spaces to make the text appear as it's always centered.
This uses the plugin I wrote for your previous question
$.fn.dots = function(time, dots) {
return this.each(function(i,el) {
clearInterval( $(el).data('dots') );
if ( time !== 0 ) {
var d = 0;
$(el).data('dots', setInterval(function() {
$(el).val(function(_,v) {
if (d < dots) {
d++;
return ' ' + v + '.';
} else {
d = 0;
return v.substring(dots, v.length - dots)
}
})
}, time));
}
});
}
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).val('Proccessing').prop('disabled',true).dots(600, 3);
});
});
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="payDots" type="button" value="Pay" class="button">
You can find updated code below
Click Here
HTML Code
<button id="payDots">
<span>Pay</span>
</button>
JS Code
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
$('button').css('padding-left','100px','important');
var dot = '.';
if(dots < 3) {
$('#payDots').text('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').text('processing');
dots = 0;
}
}
CSS Code
button{
text-align: left;
width: 300px;
font-size: 20px;
position:relative;
padding-left:130px;
}

Jquery number counter for updates

I have this jquery functions. I want to make it just one function so I can get thesame results by just calling a function and passing some arguements.
As you can see, the function does basically the same thing counting numbers. I would love to just have one function , then parse out arguments to get the same results. something like startcount(arg1, arg2);
var one_countsArray = [2,4,6,7,4252];
var two_countsArray = [3,3,4,7,1229];
var sumemp = one_countsArray.reduce(add, 0);
var sumallis = two_countsArray.reduce(add, 0);
function add(a, b) {
return a + b;
}
var count = 0;
var inTv = setInterval(function(){startCount()},100);
var inTv2 = setInterval(function(){startCount2()},100);
function startCount()
{
if(count == sumemp) {
clearInterval(inTv);
} else {
count++;
}
$('.stats_em').text(count);
}
var count2 = 10;
function startCount2()
{
if(count2 == sumallis) {
clearInterval(inTv2);
} else {
count2++;
}
$('.stats_iss').text(count2);
}
div {
padding:50px 0;
background: #000000;
color: #ffffff;
width: 100px;
height:100px;
border-radius:50%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="stats_em"></div>
<div class="stats_iss"></div>
How about a very simple jquery plugin
$.fn.countTo = function(arrNums){
var self = this;
function add(a,b){
return a+b;
}
var current = 0;
var max = arrNums.reduce(add,0);
var int = setInterval(function(){
if(current == max)
clearInterval(int);
else
current++;
self.text(current);
},100);
return this;
}
$('.stats_em').countTo([2,4,6,7,4252]);
$('.stats_iss').countTo([3,3,4,7,1229]);
div {
padding:50px 0;
background: #000000;
color: #ffffff;
width: 100px;
height:100px;
border-radius:50%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="stats_em"></div>
<div class="stats_iss"></div>
When you notice you're rewriting chunks of similar code, moving to one generic function is the right approach! The best way to start is by trying to determine what you're parameters would be:
count and count2 show that you need a start count for your timer to start at
sumemp and sumpallis show that you need to be able to specify a maximum count
inTv and inTv show that you need to be able to set the interval
$('.stats_iss') and $('.stats_em') show that you need to be able to determine the output element
This means your final class, function or jquery extension will at least have a signature that resembles this:
function(startCount, maximumCount, interval, outputElement) { }
Once you've written this, you can paste in the code you already have. (I've replaced your setInterval with a setTimeout, other than that, not much changed)
var createCounter = function(start, max, interval, outputElement) {
var count = start;
var timeout;
var start = function() {
count += 1;
outputElement.text(count);
if (count < max) {
timeout = setTimeout(start, interval);
}
}
var stop = clearTimeout(timeout);
return {
start: start,
stop: stop
}
}
var one_countsArray = [2, 4, 6, 7, 300];
var two_countsArray = [3, 3, 4, 7, 100];
var sumemp = one_countsArray.reduce(add, 0);
var sumallis = two_countsArray.reduce(add, 0);
function add(a, b) {
return a + b;
}
var counters = [
createCounter(0, sumemp, 100, $('.stats_em')),
createCounter(10, sumallis, 100, $('.stats_iss'))
];
counters.forEach(function(counter) {
counter.start();
});
div {
padding: 50px 0;
background: #000000;
color: #ffffff;
width: 100px;
height: 100px;
border-radius: 50%;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div class="stats_em"></div>
<div class="stats_iss"></div>

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

How can I add a button to display a timer when clicked

I have a simple memory game that is won by matching two letter. How can I add a button to start a timer that displays some where by the game, and when you win the timer stops but shows best times, furthermore, you can keep count to beat your best time. Also, how do I change my letter to substitute for images?
<title>Memory</title>
</head>
<body>
<div id="container">
<div id="header">
Memory!
</div>
<div id="content">
<table id="gameBoard">
<tbody>
</tbody>
</table>
<button id="playAgain">Play Again</button>
</div>
</div>
body {
font-family:copperplate;
font-size: 0.9em;
background-color:#ccc;
}
html, body {
margin:0;
padding:0;
height:100%;
}
#container {
width:950px;
min-width:950px;
background-color:#fff;
margin:0 auto;
min-height:100%;
}
#header {
font-size:4em;
line-height:95px;
text-align:center;
border-bottom:1px solid #000;
}
#content {
clear:both;
border-top:1px solid #000;
padding-top:5px;
padding:10px;
text-align:center;
}
h1 {
text-transform: capitalize;
}
#gameBoard {
margin-left:auto;
margin-right:auto;
margin-bottom:25px;
}
.card {
width:100px;
height:100px;
border:1px solid #000;
cursor: pointer;
}
.down {
background-color: #E8DD5B;
}
.up {
background-color: #ccc;
line-height: 100px;
text-align:center;
font-size:5em;
}
button {
font-size:2em;
padding:5px;
background-color:#E97A54;
}
$(function() {
var cards = [
{ id: 1, matchesId: 2, content: "A" },
{ id: 2, matchesId: 1, content: "A" },
{ id: 3, matchesId: 4, content: "B" },
{ id: 4, matchesId: 3, content: "B" },
{ id: 5, matchesId: 6, content: "C" },
{ id: 6, matchesId: 5, content: "C" },
{ id: 7, matchesId: 8, content: "D" },
{ id: 8, matchesId: 7, content: "D" },
{ id: 9, matchesId: 10, content: "E" },
{ id: 10, matchesId: 9, content: "E" },
{ id: 11, matchesId: 12, content: "F" },
{ id: 12, matchesId: 11, content: "F" }
];
var shuffledCards = [];
var cardToMatchElement;
setupGame();
$("#playAgain").click(function() {
setupGame();
});
function setupGame() {
cardToMatchElement = null;
shuffleCards();
dealCards();
}
function shuffleCards() {
shuffledCards = [];
for(var i = 0; i < cards.length; i++) {
var randomCardIndex = getRandomCardIndex();
while($.inArray(randomCardIndex,shuffledCards) != -1) {
randomCardIndex = getRandomCardIndex();
}
shuffledCards.push(randomCardIndex);
}
}
function getRandomCardIndex() {
return Math.floor((Math.random() * cards.length));
}
function dealCards() {
setupGameBoard();
attachCardEvents();
}
function attachCardEvents() {
$(".card").click(function() {
var selectedCardElement = $(this);
var selectedCard = getCardFromElement(selectedCardElement);
flipCard(selectedCardElement, selectedCard);
if(cardToMatchElement) {
var cardToMatch = getCardFromElement(cardToMatchElement);
if(cardToMatch.matchesId == selectedCard.id) {
selectedCardElement.off();
cardToMatchElement.off();
cardToMatchElement = null;
}
else {
$.blockUI({ message: "", overlayCSS : { backgroundColor: '#fff', cursor:'normal', opacity:0.5 } });
setTimeout(function() {
flipCard(selectedCardElement, selectedCard);
flipCard(cardToMatchElement, cardToMatch);
cardToMatchElement = null;
$.unblockUI();
},1000);
}
}
else {
cardToMatchElement = selectedCardElement;
}
});
}
function getCardFromElement(cardElement) {
return cards[cardElement.attr("data-cardindex")];
}
function flipCard(cardElement, card) {
if(cardElement.hasClass("down")) {
cardElement.removeClass("down").addClass("up");
cardElement.html(card.content);
}
else {
cardElement.removeClass("up").addClass("down");
cardElement.html("");
}
}
function setupGameBoard() {
var numberColumns = 4;
var tableBody = "";
var tableRow = "<tr>";
$.each(shuffledCards, function(index, card) {
tableRow += "<td><div class='card down' data-cardindex='" + shuffledCards[index] + "'>&nbsp</div></td>";
if(index > 0 && (index + 1) % numberColumns == 0) {
tableRow += "</tr>";
if(index < cards.length - 1) {
tableRow += "<tr>";
}
}
if(index == cards.length - 1 && (index + 1) % numberColumns != 0) {
tableRow += "</tr>";
}
tableBody += tableRow;
tableRow = "";
});
$("#gameBoard tbody").html(tableBody);
}
});
http://jsfiddle.net/Brannan2/VkKRa/1/
To create a timer call below function on your button click (id is some global js variable)
function createTimer() {
id = setInterval(function(){
var secondEl = document.getElementById('second');
if (secondEl.value == null || secondEl.value == "") {
secondEl.value = 0;
}
var seconds = parseInt(secondEl.value) + 1;
if (seconds == 60) {
seconds = 0;
var minuteEl = document.getElementById('minute');
if (minuteEl.value == null || minuteEl.value == "") {
minuteEl.value = 0;
}
var minutes = parseInt(minuteEl.value) + 1;
if (minutes == 60) {
minutes = 0;
var hourEl = document.getElementById('hour');
if (hourEl.value == null || hourEl.value == "") {
hourEl.value = 0;
}
hourEl.value = parseInt(hourEl.value) + 1;
}
minuteEl.value = minutes;
}
secondEl.value = seconds;
},1000);
}
For my sample I have created three input types in html with ids 'hour','minute' and 'second'. You can create any other based on UI need and update function accordingly.
To stop timer just remove the setInterval function as shown below
window.clearInterval(id);
Once you have stop the watch you can calculate total times easily by using below formula
var totalTime = (hours * 3600) + (minutes * 60) + seconds;
This will return the total time in seconds. Now to get best times, I think you have to use localStorage so that you can store best times in client browser and refer to it later whenever user returns again to play your game.
To substitute letter with images, there can be many ways. For e.g. you can add a css class to the element which will set the background image for you or you can directly use a img tag in your div with image location. Its totally up to you. I am not sure though why you want to show image with your current requirement.

Categories