How to display divs in loop using javascript or jquery - javascript

This code works perfect for displaying one notification div but i want to display this notification div ten times one after another.
<button onclick="myFunction()">Show Notification</button>
<div id="container">This is First Notification</div>
<script>
function myFunction() {
var x = document.getElementById("container")
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
</script>

You can use recursion
function showTimes(count, times) {
$('#container').show();
$('.info').append("show number" + (count + 1) + "<br>");
console.log('func');
setTimeout(function() {
$('#container').hide()
console.log('count: ' + count + '; times: ' + times);
if (count >= times) {
return;
} else {
setTimeout(showTimes(count + 1, times), 2000);
}
}, 3000);
}
$(document).ready(function() {
showTimes(0, 10);
});
jsfiddle(press RUN at the top)
https://jsfiddle.net/ShinShil/v8ftcnLz/2/

Related

Loop function to run 25 times but at 2 second interval

I have the following function to open an iframe , i need to run this function 25 times and open 25 iframes with different url parameter paths.
After the function is ran , i will get some content , then close the iframe , then reopen a new iframe using a url with the next parameter of "SEQNO=100" , to 101 , 102 etc all the way to 124.
How can i get this to work , i tried setting a loop but it opened all frames at same time
function backupMSG() {
// OPEN NEW IFRAME EACH TIME FUNCTION RUNS - ITERATE "SEQNO=100 to SEQNO+125"
$('body').append("<iframe src='" + baseURLDynamic + "/" + year + "/csetup?L=" + league_id + "&C=HMPGMSG&SEQNO=100&PRINTER=1' id='iframe'></iframe>");
$('body').append("<iframe src='" + baseURLDynamic + "/" + year + "/csetup?L=" + league_id + "&C=HMPGMSG&SEQNO=101&PRINTER=1' id='iframe'></iframe>");
$('body').append("<iframe src='" + baseURLDynamic + "/" + year + "/csetup?L=" + league_id + "&C=HMPGMSG&SEQNO=102&PRINTER=1' id='iframe'></iframe>");
// posted 3 urls for example - need to loop over 25 different parameters
$("#iframe").on("load", function () {
// Get some content from iframe
setTimeout(function () {
console.log("Ran 1 Time") // COUNT HOW MANY TIMES HAS THIS FUNCTION RAN
$("#iframe").remove();
}, 600);
setTimeout(function () {
backupMSG(); //RUN FUNCTION 25 TIMES AT INTERVAL OF 2 SECONDS
}, 2000);
});
}
I tried loops like below but both result in console log of all 25 at same time and i want a delay before it loops through the function again
n=25;
for (let i = 0; i < n; i++) {
setTimeout(function () {
console.log("Hi!"+i)
}, 2000);
}
n=25;
setTimeout(function () {
for (let i = 0; i < n; i++) {
console.log("Hi!"+i)
}
}, 2000);
var i=1,n=25;
setInterval(function(){
if(i<=n){
console.log(i);
i++;
}else{
clearInterval();
}
},2000)
function backupMSG(id) {
$("body").append(
"<iframe src='https://picsum.photos/id/" +
id +
"/200/300' id='iframe'></iframe>"
);
$("#iframe").on("load", function () {
setTimeout(function () {
console.log("Run " + id + " Time");
$("#iframe").remove();
}, 600);
});
}
let startId = 1;
let count = 3;
let interval = setInterval(() => {
if (startId >= count) clearInterval(interval)
backupMSG(startId);
startId++;
}, 3000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Issue linking images to dynamically created jquery elements

So, I'm very new, so apologies if this is a silly question. I have worked out a Trivia Quiz for my learning to code classes I'm taking. I want to display an image on the confirmation screen that shows whether the user was right or wrong. I think the code is correct-ish? I'm not sure what isn't working.
I left out the main Question and answer object for space. Sorry if I didn't format this ideally? I'm still kinda figuring out how things work here.
Here is my code for reference:
//array to help me iterate and insert images
var imgArray = ["question1", "question2", "question3", "question4", "question5", "question6", "question7", "question8", "question9", "question10", "question11", "question12", "question13"];
var currentQuestion = 0;
var win = 0;
var lose = 0;
var unanswered = 0;
var time = 30;
//set up divs to contain our info
var rightDiv = $("<div class='rightAns'></div>");
var timerDiv = $("<div class='countdown'><h3></h3></div>");
var questionDiv = $("<div class='question'><h1></h1></div><br>");
var answerDiv = $("<div class='answers'></div>");
//object keys to return questions in order
var keys = Object.keys(questions);
var key = keys[n];
var n = 0;
//function to setup and restart game
function reset() {
$("#start-button").hide("slow");
$("#start-here").hide("slow");
win = 0;
lose = 0;
unanswered = 0;
n = 0;
key = keys[n];
currentQuestion = 0;
$("#question-block").empty();
var reset = function () {
time = 30;
$(".rightAns").empty();
$(".rightAns").remove();
// $("#image").empty();
$("#time-remaining").append(timerDiv);
$(".countdown h3").html("Time Remaining: " + time);
$("#question-block").append(questionDiv);
$("#question-block").append(answerDiv);
}
reset();
//function to show questions
function showQuestion() {
$(".question h1").html(questions[key].question);
for (var i = 0; i < questions[key].answers.length; i++) {
$(".answers").append("<button class='answer btn btn-danger btn-lg m-1'>" + questions[key].answers[i] + "</button>");
}
$(".answers button").on("click", function () {
var selected = $(this).text();
//if then to check question correctness
if (selected === questions[key].correct) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("That's Correct!!");
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
win++;
currentQuestion++;
} else {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$(answerDiv).remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").text("Nope! The correct answer was: " + questions[key].correct);
$("#image").html('<img src = ".assets/images/' + imgArray[currentQuestion] + '" width = "400px">');
lose++;
currentQuestion++;
}
n++;
key = keys[n];
//checking to see if there are more questions left
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
});
}
showQuestion();
var counter = setInterval(count, 1000);
//show time remaining for each question
function count() {
time--;
$(".countdown h3").html("Time Remaining: " + time);
if (time < 1) {
clearInterval(counter);
$(timerDiv).remove();
$(questionDiv).remove();
$(".answers button").remove();
$("#correct-answer").append(rightDiv);
$(".rightAns").html("You took too long! The correct answer was: " + questions[key].correct);
unanswered++;
n++;
key = keys[n];
if (checkForLast()) {
finalScore();
} else {
setTimeout(countReset, 3 * 1000);
setTimeout(reset, 3 * 1000);
setTimeout(showQuestion, 3 * 1000);
}
}
}
function checkForLast() {
if (key === undefined) {
return true;
}
return false;
}
//timer for the message after you choose your answer
function countReset() {
counter = setInterval(count, 1000);
}
//showthe final score screen
function finalScore() {
$(".rightAns").remove();
$("#image").empty();
$("#question-block").prepend("<h2>Unanswered: " + unanswered + "</h2>");
$("#question-block").prepend("<h2>Incorrect: " + lose + "</h2>");
$("#question-block").prepend("<h2>Correct: " + win + "</h2>");
$("#start-button").show();
$("#start-here").show();
}
};
//function to start game on button click
$(document).on("click", "#start-button", reset);
});
After tinkering for a bit, I dropped the "." at the beginning of the call and added the .jpg to the section after imgArray[currentQuestion]. That solved it. Thanks for the suggestions.

Scope of undefined in 2nd round of a Javascript & JQuery Trivia game

My game works until summary page start link is clicked. Then I get undefined variables when trying to play again.
I'm new to JS so I'm sure it is a stupid user error and not handling scope correctly.
If I comment the location.reload at the bottom of the javascript it works just fine after the timer is up, but the coding assignment wants us to not do a refresh. I appreciate any help!
$(document).ready(function() {
var correctAnswers = 0;
var incorrectAnswers = 0;
var unansweredQuestions = 0;
var timeRemaining = 16;
var intervalID;
var indexQandA = 0;
var answered = false;
var correct;
var start = $(".start").html("Start Game");
start.on("click", startGame);
var triviaQandA = [{
question: "What is the fastest animal?",
answer: ["cheetah", "turtle", "giraffe", "elephant"],
correct: "0",
image: ("assets/images/circle.png")
}, {
question: "When you are blue you turn?",
answer: ["red", "green", "blue", "yellow"],
correct: "2",
image: ("assets/images/dot.jpg")
}];
function startGame() {
$(".start").hide();
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
loadQandA();
}
function loadQandA() {
answered = false;
timeRemaining = 16;
intervalID = setInterval(timer, 1000);
if (answered === false) {
timer();
}
correct = triviaQandA[indexQandA].correct;
var question = triviaQandA[indexQandA].question;
$(".question").html(question);
for (var i = 0; i < 4; i++) {
var answer = triviaQandA[indexQandA].answer[i];
$(".answers").append("<h4 class = answersAll id =" + i + ">" + answer + "</h4>");
}
$("h4").click(function() {
var id = $(this).attr("id");
if (id === correct) {
answered = true;
$(".question").text("The answer is: " + triviaQandA[indexQandA].answer[correct]);
correctAnswer();
} else {
answered = true;
$(".question").text("You chose: " + triviaQandA[indexQandA].answer[id] + " the correct answer is: " + triviaQandA[indexQandA].answer[correct]);
incorrectAnswer();
}
console.log(correct);
});
}
function timer() {
if (timeRemaining === 0) {
answered = true;
clearInterval(intervalID);
$(".question").text("The correct answer is: " + triviaQandA[indexQandA].answer[correct]);
unAnswered();
} else if (answered === true) {
clearInterval(intervalID);
} else {
timeRemaining--;
$(".timeRemaining").text("You have " + timeRemaining);
}
}
function correctAnswer() {
correctAnswers++;
$(".timeRemaining").text("You are spot on!!!").css({
"color": "#3d414f"
});
reset();
}
function incorrectAnswer() {
incorrectAnswers++;
$(".timeRemaining").text("You are sooo wrong").css({
"color": "#3d414f"
});
reset();
}
function unAnswered() {
unansweredQuestions++;
$(".timeRemaining").text("You didn't choose anything...").css({
"color": "#3d414f"
});
reset();
}
function reset() {
$(".answersAll").remove();
$(".answers").append("<img class=answerImage width='150' height='150' src='" + triviaQandA[indexQandA].image + "'>");
indexQandA++;
if (indexQandA < triviaQandA.length) {
setTimeout(function() {
loadQandA();
$(".answerImage").remove();
}, 2000);
} else {
setTimeout(function() {
$(".question").remove();
$(".timeRemaining").remove();
$(".answerImage").remove();
$(".answers").append("<h4 class = answersAll end>Correct answers: " + correctAnswers + "</h4>");
$(".answers").append("<h4 class = answersAll end>Wrong answers: " + incorrectAnswers + "</h4>");
$(".answers").append("<h4 class = answersAll end>Unanswered questions: " + unansweredQuestions + "</h4>");
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
// setTimeout(function() {
// location.reload();
// }, 5000);
var start = $(".start-over").html("Start Game");
start.on("click", startGame);
}, 2000);
}
};
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="start"></div>
<h1>Trivia</h1>
<h5 class="timeRemaining"></h5>
<h3 class="question"></h3>
<div class="answers"></div>
<div class="start-over"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
Here's an inline link to my Codepen.
The problem comes from the fact that you increment indexQandA on each question, but never reset it. You need to reset it to 0 when starting a new game - that is, in the else clause of the reset function you need to put indexQandA=0 alongside where you reset the other variables to 0.
There is a further problem when this is done though, the quiz runs ok a second time now, but doesn't display the questions any more. That's because you've removed the .question element during reset. You don't need to do this, you can just hide it, then display it again when the game restarts.
Actually, it transpired there were further problems. I've solved it - run through the game about 5 times in a row with no obvious problems - with the following code (I make no claim that this is the correct code to do it, it's just minimal changes to your existing code to get it to work):
$(document).ready(function() {
var correctAnswers = 0;
var incorrectAnswers = 0;
var unansweredQuestions = 0;
var timeRemaining = 16;
var intervalID;
var indexQandA = 0;
var answered = false;
var correct;
var start = $(".start").html("Start Game");
start.on("click", startGame);
$(".start-over").on("click", startGame);
var triviaQandA = [{
question:"What is the fastest animal?",
answer:["cheetah","turtle","giraffe","elephant"],
correct:"0",
image: ("assets/images/circle.png")
}, {
question:"When you are blue you turn?",
answer:["red","green","blue","yellow"],
correct:"1",
image: ("assets/images/dot.jpg")
}];
function startGame() {
$(".summary").hide();
$(".start").hide();
$(".timeRemaining").show();
$(".question").show();
$(".answers").show();
$(".start-over").hide();
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
loadQandA();
}
function loadQandA() {
answer = [];
answered = false;
timeRemaining = 16;
timer();
intervalID = setInterval(timer, 1000);
/*if (answered === false) {
timer();
}*/
correct = triviaQandA[indexQandA].correct;
var question = triviaQandA[indexQandA].question;
$(".question").html(question);
for (var i = 0; i < 4; i++) {
var answer = triviaQandA[indexQandA].answer[i];
$(".answers").append("<h4 class = answersAll id =" + i + ">" + answer + "</h4>");
}
$("h4").click(function() {
var id = $(this).attr("id");
if (id === correct) {
answered = true;
$(".question").text("The answer is: " + triviaQandA[indexQandA].answer[correct]);
correctAnswer();
} else {
answered = true;
$(".question").text("You chose: " + triviaQandA[indexQandA].answer[id] + " the correct answer is: " + triviaQandA[indexQandA].answer[correct]);
incorrectAnswer();
}
console.log(correct);
});
}
function timer() {
if (timeRemaining === 0) {
answered = true;
//clearInterval(intervalID);
$(".question").text("The correct answer is: " + triviaQandA[indexQandA].answer[correct]);
unAnswered();
} else if (answered === true) {
//clearInterval(intervalID);
} else {
timeRemaining--;
$(".timeRemaining").text("You have " + timeRemaining);
}
}
function correctAnswer() {
correctAnswers++;
$(".timeRemaining").text("You are spot on!!!").css({
"color": "#3d414f"
});
reset();
}
function incorrectAnswer() {
incorrectAnswers++;
$(".timeRemaining").text("You are sooo wrong").css({
"color": "#3d414f"
});
reset();
}
function unAnswered() {
unansweredQuestions++;
$(".timeRemaining").text("You didn't choose anything...").css({
"color": "#3d414f"
});
reset();
}
function reset() {
clearInterval(intervalID);
$(".answersAll").remove();
$(".answers").append("<img class=answerImage width='150' height='150' src='" + triviaQandA[indexQandA].image + "'>");
indexQandA++;
if (indexQandA < triviaQandA.length) {
setTimeout(function () {
loadQandA();
$(".answerImage").remove();
}, 2000);
} else {
setTimeout(function() {
$(".summary").show();
$(".question").hide();
$(".timeRemaining").hide();
$(".answers").hide();
$(".start-over").show();
$(".answerImage").remove();
$(".summary").append("<h4 class = answersAll end>Correct answers: " + correctAnswers + "</h4>");
$(".summary").append("<h4 class = answersAll end>Wrong answers: " + incorrectAnswers + "</h4>");
$(".summary").append("<h4 class = answersAll end>Unanswered questions: " + unansweredQuestions + "</h4>");
correctAnswers = 0;
incorrectAnswers = 0;
unansweredQuestions = 0;
indexQandA=0;
// setTimeout(function() {
// location.reload();
// }, 5000);
$(".start-over").html("Start Game");
start.on("click", startGame);
}, 2000);
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!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">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="start"></div>
<h1>Trivia</h1>
<h5 class="timeRemaining"></h5>
<h3 class="question"></h3>
<div class="answers"></div>
<div class="summary"></div>
<div class="start-over"></div>
</body>
</html>
There were 2 main problems with your code as it initially was:
most seriously, you were adding startGame as the click handler for the "start over" button each time the reset function was called. As a result, multiple such handlers were getting added by the time you played a 3rd, 4th, 5th... time, with the result that the startGame function was getting called multiple times, which was why you were getting the answer options printed multiple times. I've fixed this by removing that section of code entirely, and adding the event listener once, on page load.
your timer was also going a bit haywire, as you were calling the timer function manually as well as using setInterval to run it every second, and nor were you always clearing it when the question was answered. I've simplified this greatly, and made it work, just by setting the timer in loadQandA, as before, and clearing it in the reset function.
You will see that I've mainly just commented things out, rather than removed them - this will hopefully make it easier to see what I've removed.

Button Click Event not working

I just write some JS code for click listener, if a button is clicked more than 5 times in 3 seconds then alert will say you wan otherwise you lost.
But I am getting every time YOU LOST!!
<head>
</head>
<body>
<button>Click!!</button>
<script>
let counter =0;
document.querySelector('button').addEventListener('Click', () => {
counter++;
});
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
</script>
</body>
you may use lowercase 'click' not 'Click', you didn't call your click event anytime in your sample code.
https://developer.mozilla.org/en-US/docs/Web/Events/click
Minor change on your source code. Now working fine.
let counter =0;
document.querySelector('button').addEventListener('click', () =>counter++);
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
.col {
float: left;
width: 20%;
}
.row {
width: 100%;
clear:both;
display:block;
}
<button>Click!!</button>
I updated your code, two things I noticed were you used an uppercase for your click event:
addEventListener('Click'
and I also changed the if to alert 'you won' if counter was greater than or equal to 5
if(counter >= 5)
Here's a working fiddle
http://jsfiddle.net/fkvvc1f0/1/
This works fine, Working Demo
I changed "Click" to "click", small case only.
addEventListener('click', () => {})
Might want to check out : JavaScript event listeners are case sensitive.
<button>Click!!</button>
<script>
let counter =0;
document.querySelector('button').addEventListener('click', () => {
counter++;
});
setTimeout(() => {
if(counter > 5) {
alert('You Won!!' + counter);
} else {
alert('You Lost!!' + counter);
}
},3000)
</script>
Result :
LOST :
WON :
You should use external JavaScript and CSS, for caching reasons, but I think you want to see this:
function lameGame(clickElement){
let c = 0;
setTimeout(() => {
if(c > 5) {
alert('You Won!!' + c); // never use alert in real world
}
else{
alert('You Lost!!' + c); // never use alert in real world
}
lameGame(clickElement);
}, 3000);
clickElement.onclick = function(){
c++;
}
}
lameGame(document.querySelector('button'));

JavaScript Alert Box Popup Issue

I am having an issue with an Alert Box not appearing on the screen after I click a submit button. I have searched this forum and online for answers and I don't see what is wrong with my code. As with most of my issues, the solution is probably a simple fix but I can't seem to find the issue after going through my code. Any help is appreciated.
javascript code
<script type="text/javascript">
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
}
</script>
<script type="text/javascript">
function runClock() {
seconds++;
document.getElementById('quizclock').value=seconds;
}
</script>
<script type="text/javascript">
function startClock() {
showQuiz();
clockId=setInterval ("runClock()", 1000);
}
</script>
function resetQuiz() {
document.quiz.quizclock.value = 0;
for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=false;
document.quiz.stop.disabled = true;
}
function showQuiz() {
document.getElementById("quiztable").style.visibility="visible";
document.quiz.start.disabled = true;
document.quiz.stop.disabled = false;
}
function hideQuiz() {
document.getElementById("quiztable").style.visibility="hidden";
}
function gradeQuiz() {
correct=0;
if (document.quiz.q1[1].checked) correct++;
if (document.quiz.q2[3].checked) correct++;
if (document.quiz.q3[0].checked) correct++;
if (document.quiz.q4[3].checked) correct++;
if (document.quiz.q5[2].checked) correct++;
document.getElementById("cor1").style.backgroundColor="yellow";
document.getElementById("cor2").style.backgroundColor="yellow";
document.getElementById("cor3").style.backgroundColor="yellow";
document.getElementById("cor4").style.backgroundColor="yellow";
document.getElementById("cor5").style.backgroundColor="yellow";
for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=true;
return correct;
}
html for button that pops up the alert
<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>
Probably you have a variable undefined, check this working demo
function gradeQuiz() {
return 'something';
}
var clockId, i = timer = 0;
clockId = setInterval(function() {
i++;
$('h2').text(i);
}, 200);
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have ' + correctAns + ' correct of 5 in ' + timer + ' seconds');
}
$('button').on('click', stopClock);
http://jsbin.com/toyibekivu/edit?html,js,output
You need to define your variables and use seconds in alert.
Change your functions to:
var clockId;
var seconds = 0;
function stopClock() {
clearInterval (clockId);
correctAns = gradeQuiz();
alert('You have' + correctAns + 'correct of 5 in' + seconds + 'seconds');
}
function startClock() {
showQuiz();
seconds = 0;
clockId=setInterval (runClock, 1000);
}
If you remove
alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
from your stopClock() function no alert will appear on the screen.

Categories

Resources