Text changing animation using Javascript - javascript

I am trying to create a changing text for every 3 seconds. But it seems just to run once and then it stops doing anything. My code:
HTML
<div class="output">
<h2>True Multi-Purpose Theme for
<span class="changingtext">Business</span>
and More
</h2>
</div>
JavaScript
let newText = document.querySelector('.changingtext')
setInterval(function() {
if (newText.innerHTML = 'Business'){
newText.innerHTML = 'Agencies';
}
else if (newText.innerHTML = "Agencies"){
newText.innerHTML = 'Startups';
}
else {
newText.innerHTML = 'Business';
}
}, 3000)

The problem is that you are using assignation instead of comparaison in your if
WRONG
if(newText.innerHTML = 'Business'){
CORRECT
if (newText.innerHTML === 'Business') {
let newText = document.querySelector('.changingtext')
setInterval(function() {
if (newText.innerHTML === 'Business') {
newText.innerHTML = 'Agencies';
} else if (newText.innerHTML === "Agencies") {
newText.innerHTML = 'Startups'
} else {
newText.innerHTML = 'Business'
}
}, 3000)
<div class="output">
<h2>True Multi-Purpose Theme
<be>
for
<span class="changingtext">Business</span> and More
</h2>
</div>
Also, the following could be better :
const text = document.querySelector('.changingtext')
const texts = [
'Business',
'Agencies',
'Startups',
];
function nextText() {
const actualTextIndex = texts.findIndex(x => text.innerText === x);
const newTextIndex = actualTextIndex + 1 === texts.length ? 0 : actualTextIndex + 1;
text.innerText = texts[newTextIndex];
}
setInterval(nextText, 3000)
<div class="output">
<h2>True Multi-Purpose Theme
<be>
for
<span class="changingtext">Business</span> and More
</h2>
</div>
You can improve it again by :
Creating an utility function that will work in standalone getting the selector, the time between a text change and the list of texts to loop from
Gl

Related

how to display score on different html page after clicking a button on different page

I'm building a small quiz app, and want to display the user score on a different html page immediately the user finished answering the questions. what am getting right now the user finish answering the questions the in which the score is suppose to display loads and open without the score displayed.
`
<body>
<div class="quiz-title">
<h1>JS Quiz</h1>
</div>
<div class="container">
<h2 id="score-board">00</h2>
<div id="questions"></div>
<div id="answers">
</div>
<button type="submit"class="nbtn">Play</button>
</div>
<script src="quiz.js"></script>
<!-- <script type="text/javascript" src="quiz1.js"></script> -->
</body>
the page to display the score
<body>
<h2 id="score-board">00</h2>
<div>
<button id="play-btn">play</button>
</div>
<script src="quiz.js"></script>
<!-- <script type="text/javascript" src="quiz1.js"></script> -->
</body>
var questionElement = document.getElementById('questions');
var answerElement = document.getElementById('answers');
var scoreBoard = document.querySelector('#score-board');
const state = {
currentQuestionIndex: 0,
score: 0
};
var questions = [
{ question: " 1. javaScript is an....... language?",
answers: [ "object-oriented", "object-based", "procedural", "none of the above"],
correct: 1
},
{ question: " 2.which of the following keywords is used a define variable in javaScript",
answers: [ "var", "let", "both A and B", "none of the above"],
correct: 2
},
{
question: "3. which of the following methods is used to HTML elements using javaScript",
answers: ["getElementsById", "getElementByClassName", "both A and B", "none of the above"] ,
correct: 2
}
];
function showQuestion(questionIndex){
const question = questions[questionIndex];
let qDiv = document.createElement('div');
let p = document.createElement('p');
questionElement.innerHTML = "";
answerElement.innerHTML = "";
p.textContent = question.question;
qDiv.appendChild(p);
questionElement.appendChild(qDiv);
question.answers.forEach((answers, answerIndex) =>{
const $input = document.createElement('input');
const $label = document.createElement('label');
$label.appendChild($input);
$label.appendChild(document.createTextNode(answers));
$input.name = `question${questionIndex}`;
$input.type = 'radio';
$input.value = answerIndex;
answerElement.append($label);
// if ($input.checked === false) {
// console.log('select answer');
// } else{
// showQuestion(state.currentQuestionIndex);
// }
});
};
showQuestion(0);
var nBtn = document.querySelector('.nbtn');
nBtn.addEventListener('click', function(){
state.currentQuestionIndex += 1;
if (state.currentQuestionIndex === questions.length) {
removeLastQuestion();
scorePage();
showScores();
} else{
showQuestion(state.currentQuestionIndex)
}
});
const $answers = document.getElementById("answers");
$answers.addEventListener("change", (event) => {
const currentQuestion = questions[state.currentQuestionIndex];
const selectedAnswerIndex = Number(event.target.value);
const correctAnswerIndex = currentQuestion.correct;
const isCorrect = selectedAnswerIndex === correctAnswerIndex;
state.score += isCorrect ? 1 : 0;
// if (isCorrect) {
// var scoreBoard = document2.querySelector('.score-board');
// // scoreBoard.textContent = state.score;
// // console.log("correct answer");
// } else {
// var scoreBoard = document.querySelector('.score-board');
// // scoreBoard.textContent = state.score += 0;
// // console.log("wrong answer");
// }
});
function showScores() {
if (state.currentQuestionIndex === questions.length) {
scoreBoard.innerHTML = `${state.score}/${questions.length}`
}
}
function removeLastQuestion(){
if (state.currentQuestionIndex > questions.length - 1) {
questionElement.innerHTML = "";
answerElement.innerHTML = "";
}
}
function scorePage() {
if (state.currentQuestionIndex > questions.length -1) {
window.location.href = 'index23.html';
// scoreBoard = document.querySelector('#score-board');
// scoreBoard.innerText = `${state.score}/${questions.length}`;
}
}
// const playBtn = document.querySelector('#play-btn');
// playBtn.addEventListener('click', showQuestion);
`

Async/await function to show, wait, hide overlay not working in javascript

I'm having a problem with showing an overlay div element and then hiding it again after the runSearch() function has completed. In short, the overlay does not appear at all.
What the overlay should look like if it worked:
If I had to guess, I believe it could relate to a misunderstanding about how to implement async/await correctly in javascript.
Since I am limited for space here, the full Github project is accessible as a fully deployed page here, if you need more context. However, the most relevant excerpts are below:
The overlay div element in index.html:
<div class="overlay d-flex justify-content-center align-items-center">
<h5>Please wait...</h5>
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
The overlay in CSS:
.overlay {
background-color:#EFEFEF;
position: fixed;
width: 100%;
height: 100%;
z-index: 1000;
left: 0px;
display: none!important;
/* without !important, the overlay would immediately kick into effect */
}
The JS functions which show and hide the overlay when called upon:
function loadingOverlayOn() {
document
.getElementsByClassName("overlay")[0]
.style.display = 'block'
}
function loadingOverlayOff() {
document
.getElementsByClassName("overlay")[0]
.style.display = 'none'
}
JS with respect to button #1:
cityInstanceBtn.addEventListener('click',async function(e){
// for use in headings inside runSearch
// reset
globalCityName === null;
globalCityState === null;
globalCityCountry === null;
globalCityName = e.target.dataset.city
globalCityState = e.target.dataset.state
globalCityCountry = e.target.dataset.country
loadingOverlayOn();
await runSearch(cityName, cityState, cityCountry, cityLat, cityLng, units)
loadingOverlayOff();
})
JS with respect to button #2, which occurs inside of a temporarily displayed Bootstrap modal:
cityInstanceBtn.addEventListener('click', async function(){
myModal.hide()
globalCityName = document.getElementById(id).dataset.city
globalCityState = document.getElementById(id).dataset.state
globalCityCountry = document.getElementById(id).dataset.country
loadingOverlayOn();
await runSearch(cityName, cityState, cityCountry, cityLat, cityLng, units)
loadingOverlayOff();
})
The JS function during which the overlay should be shown, and hidden once its execution is complete:
async function runSearch(
cityName,
cityState,
country,
cityLat,
cityLng,
detectedUnits
) {
console.log("check cityState: " + cityState);
console.log("check globalCityState: " + globalCityState);
var h2Today = document.getElementById("today-title");
var h2Next5Days = document.getElementById("next-5-days-title");
if (globalCityState != "undefined" && globalCityName && globalCityCountry) {
h2Today.innerHTML = `<span class="orange">Today's</span> forecast for <span class="cornflowerblue">${globalCityName}, ${globalCityState}, ${globalCityCountry}</span>`;
h2Next5Days.innerHTML = `<span class="orange">4-day</span> outlook for <span class="cornflowerblue">${globalCityName}, ${globalCityState}, ${globalCityCountry}</span>`;
} else if (
(globalCityState = "undefined" && globalCityName && globalCityCountry)
) {
h2Today.innerHTML = `<span class="orange">Today's</span> forecast for <span class="cornflowerblue">${globalCityName},${globalCityCountry}</span>`;
h2Next5Days.innerHTML = `<span class="orange">4-day</span> outlook for <span class="cornflowerblue">${globalCityName}, ${globalCityCountry}</span>`;
}
var newSearchObject = {
cityName: cityName,
cityState: cityState,
cityCountry: country,
cityLat: cityLat,
cityLng: cityLng,
detectedUnits: detectedUnits,
};
var retrievedLocalStorage = localStorage.getItem("savedCities");
retrievedLocalStorage = JSON.parse(retrievedLocalStorage);
// const arr = retrievedLocalStorage.map(a => {a.cityLat, a.cityLng})
if (retrievedLocalStorage === null) {
localStorage.setItem("savedCities", JSON.stringify([newSearchObject]));
generatePrevCitiesList();
} else if (
retrievedLocalStorage.length > 0 &&
retrievedLocalStorage.length < 5
) {
retrievedLocalStorage.reverse();
if (
!retrievedLocalStorage.some((s) => {
return (
s.cityLat == newSearchObject.cityLat &&
s.cityLng == newSearchObject.cityLng
);
})
) {
// Check if an array of objects contains another object: https://stackoverflow.com/a/63336477/9095603
// this solution which converts objects to string first isn't entirely reliable if you can't guarantee the same order is preserved, for example: https://stackoverflow.com/a/201305/9095603
retrievedLocalStorage.push(newSearchObject);
retrievedLocalStorage.reverse();
console.log("existingSearchObject2: " + retrievedLocalStorage);
localStorage.setItem(
"savedCities",
JSON.stringify(retrievedLocalStorage)
);
}
generatePrevCitiesList();
} else if (retrievedLocalStorage.length >= 5) {
retrievedLocalStorage.reverse();
if (
!retrievedLocalStorage.some((s) => {
return (
s.cityLat == newSearchObject.cityLat &&
s.cityLng == newSearchObject.cityLng
);
})
) {
retrievedLocalStorage.push(newSearchObject);
}
while (retrievedLocalStorage.length > 5) {
retrievedLocalStorage.shift();
}
retrievedLocalStorage.reverse();
localStorage.setItem("savedCities", JSON.stringify(retrievedLocalStorage));
generatePrevCitiesList();
}
fetch(
`https://api.openweathermap.org/data/2.5/forecast?lat=${cityLat}&lon=${cityLng}&units=${detectedUnits}&appid=${apiKey}`
)
.then((response) => response.json())
.then((data) => {
console.log(data);
console.table(data.list);
console.log(JSON.stringify(data));
var timezone = data.city.timezone;
console.log({ timezone });
var country = data.city.country;
console.log({ country });
var cityName = data.city.name;
console.log({ cityName });
var datesArray = [];
console.log({ datesArray });
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
];
// var h2Today = document.getElementById('today-title')
// h2Today.innerHTML = `<span class="orange">Today's</span> forecast for <span class="cornflowerblue">${globalCityName}, ${globalCityState}, ${globalCityCountry}</span>`
// }
// h2Today.innerHTML = `<span class="orange">Today's</span> forecast for <span class="cornflowerblue">${globalCityName},${globalCityCountry}</span>`
// }
for (let i = 0; i < data.list.length; i++) {
var unixTimestamp = data.list[i].dt;
console.log(data.list[i].dt);
// you don't need it for dt_txt but if you want to use the unix timestamp in the data, you can do this conversion:
var jsTimestamp = unixTimestamp * 1000;
var date = new Date(jsTimestamp);
var basicDateLocalAU = date.toLocaleDateString("en-AU");
var basicDateLocalUS = date.toLocaleDateString("en-US");
var basicDateLocalUser = date.toLocaleDateString(`en-${country}`);
console.log(basicDateLocalAU); // Prints: 5/6/2022
console.log(basicDateLocalUS); // Prints: 6/5/2022
console.log(basicDateLocalUser); // Prints: 6/5/2022
var timeLocalAU = date.toLocaleTimeString("en-AU", {
hour: "2-digit",
minute: "2-digit",
}); // Prints: 13:10:34
// https://stackoverflow.com/a/20430558/9095603
// https://bobbyhadz.com/blog/javascript-typeerror-date-getday-is-not-a-function#:~:text=getDay%20is%20not%20a%20function%22%20error%20occurs%20when%20the%20getDay,method%20on%20valid%20date%20objects.
data.list[i].basicDateLocalAU = basicDateLocalAU;
data.list[i].basicDateLocalUS = basicDateLocalUS;
data.list[i].basicDateLocalUser = basicDateLocalUser;
data.list[i].dayOfWeekIndex = date.getDay();
data.list[i].dayOfWeekValue = days[date.getDay()];
data.list[i].basicTime = timeLocalAU;
// https://bobbyhadz.com/blog/javascript-array-push-if-not-exist
if (!datesArray.includes(basicDateLocalUser)) {
datesArray.push(basicDateLocalUser);
var dayOfWeek = days[date.getDay()];
console.log(dayOfWeek);
}
}
console.log({ date });
console.log({ data });
var datalist = data.list;
console.log({ datalist });
var obj = groupBy(datalist, "basicDateLocalAU");
console.log({ obj });
// const result = data.list.group(({ basicCalendarDateAU }) => basicCalendarDateAU);
for (let i = 0; i < obj.length; i++) {
var dayTableEle = document.querySelector(`#day${i} table`);
// var textNode = document.createTextNode(`${dayOfWeekValue}`);
dayTableEle.innerHTML = `<row><th>Time</th><th>Temp</th><th></th><th>Conditions</th><th>Humidity</th><th>Wind speed</th></row>`;
for (let j = 0; j < obj[i].length; j++) {
console.log(obj[i].length);
if (!document.querySelector(`#day${i} h5`).innerText) {
document.querySelector(
`#day${i} h5`
).innerText = `${obj[i][j].dayOfWeekValue}`;
}
if (
!document.querySelector(`#day${i} span#usercountry-dateformat`)
.innerText
) {
document.querySelector(
`#day${i} span#usercountry-dateformat`
).innerText = `${obj[i][j].basicDateLocalUser}`;
}
if (
!document.querySelector(`#day${i} span#AU-dateformat`).innerText
) {
document.querySelector(
`#day${i} span#AU-dateformat`
).innerText = `${obj[i][j].basicDateLocalAU}`;
document
.querySelector(`#day${i} span#AU-dateformat`)
.style.setProperty("display", "none");
}
if (
!document.querySelector(`#day${i} span#US-dateformat`).innerText
) {
document.querySelector(
`#day${i} span#US-dateformat`
).innerText = `${obj[i][j].basicDateLocalUS}`;
document
.querySelector(`#day${i} span#US-dateformat`)
.style.setProperty("display", "none");
}
// var kelvinToCelcius = obj[i][j].main.temp - 273.15;
var tempMetric;
var tempImperial;
var windSpeedImperial;
var windSpeedMetric;
if (units == "metric") {
var tempMetric = obj[i][j].main.temp;
tempMetric = roundedToFixed(tempMetric, 1);
var tempImperial = tempMetric * 1.8 + 32;
tempImperial = roundedToFixed(tempImperial, 1);
var windSpeedMetric = obj[i][j].wind.speed;
windSpeedMetric = roundedToFixed(windSpeedMetric, 1);
var windSpeedImperial = windSpeedMetric * 2.23694;
windSpeedImperial = roundedToFixed(windSpeedImperial, 1);
var metricDisplay = "inline";
var imperialDisplay = "none";
} else if (units == "imperial") {
var tempImperial = obj[i][j].main.temp;
tempImperial = roundedToFixed(tempImperial, 1);
var tempMetric = (tempImperial - 32) / 1.8;
tempMetric = roundedToFixed(tempMetric, 1);
var windSpeedImperial = obj[i][j].wind.speed;
windSpeedImperial = roundedToFixed(windSpeedImperial, 1);
var windSpeedMetric = windSpeedImperial / 2.23694;
windSpeedMetric = roundedToFixed(windSpeedMetric, 1);
var metricDisplay = "none";
var imperialDisplay = "inline";
}
dayTableEle.innerHTML += `
<row>
<td id="tdTime">${obj[i][j].basicTime}</td>
<td id="tdTemp">
<span class="temp-metric metric" style="display:${metricDisplay};">${tempMetric} ${tempUnitsMetric}</span>
<span class="temp-imperial imperial" style="display:${imperialDisplay};">${tempImperial} ${tempUnitsImperial}</span>
</td>
<td><img src="https://openweathermap.org/img/wn/${obj[i][j].weather[0].icon}.png" alt="weather icon"></td>
<td id="tdConditions">${obj[i][j].weather[0].description}</td>
<td id="tdHumidity">${obj[i][j].main.humidity} %</td>
<td id="tdWindSpeed">
<span class="windspeed-metric metric" style="display:${metricDisplay};">${windSpeedMetric} ${windSpeedUnitsMetric}</span>
<span class="windspeed-imperial imperial" style="display:${imperialDisplay};">${windSpeedImperial} ${windSpeedUnitsImperial}</span>
</td>
<td id="tdWindDir"><i style="transform: rotate(${obj[i][j].wind.deg}deg)" class="fa-solid fa-arrow-up"></i></td>
</row>
`;
}
}
});
}
We can see here that the event listener is properly attached - this is true of both buttons but I'll show one here just to be representative:
Full Github project is accessible as a fully deployed page here.
To reiterate, the problem is that the overlay does not appear at all during this sequence of events and I'm seeing page elements prematurely before the page is built:
loadingOverlayOn();
await runSearch(cityName, cityState, cityCountry, cityLat, cityLng, units)
loadingOverlayOff();
You are not awaiting fetch, you are using then instead.
You have to await fetch
See below example
const response = await fetch(url);
const jsonData = await response.json()

Changing color of an id with Javascript

I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the id as "deepskyblue", if it is 50 or higher it will be "orange" and lastly if it is lower than 50 it will be "crimson"(red). When i do this, it only changes my first movie's id's color. But i wanna change all of them. How can i do this?
My Website
Console.log(i)
var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name, score, img, id) {
var movies = `<div class="content"><img src="${img}" ><p>${name}</p> <p> <i class="fa fa-star" id="star"></i> <a class="scoretxt">${score}</a> </p> </div>`;
html = movies;
body.innerHTML += html;
body2.innerHTML += html;
}
function AddAllItemsToTable(TheMovies) {
movieNo = 0;
var counter = 0;
TheMovies.forEach(element => {
if (counter === 6) {
return;
}
AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
var i = document.getElementsByClassName("fa fa-star")[element.movieId];
console.log(i);
if (element.movieScore >= 70) {
i.style.color = "deepskyblue"; //good movie
} else if (element.movieScore >= 50) {
i.style.color = "orange"; //not bad
} else {
i.style.color = "crimson"; //bad movie
}
counter++;
});
}
function getAllDataOnce() {
const dbRef = ref(db);
get(child(dbRef, "Movies"))
.then((snapshot) => {
var movies = [];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload = getAllDataOnce;
<div class="body" id="body">
<div class="baslik">Opening This Week</div>
<div class="baslik2">See all</div>
<div id="week">
</div>
<div class="baslik">Editor's Picks</div>
<div class="baslik2">See all</div>
<div id="editor">
</div>
</div>
I suggest to change the logic.
Your mistake is that you use the same id several times, and it should be unique (1 element = 1 unique id).
Try to make it like this:
// AddAllItemsToTable function
if (element.movieScore >= 50 && element.movieScore < 70 ) {
i.classList.add("deepskyblue"); // good movie
} else if (element.movieScore >= 70) {
i.classList.add("orange"); // not bad
} else {
i.classList.add("crimson"); // bad movie
}
After that, add the following rules to your styles file:
.deepskyblue {
color: deepskyblue;
}
.orange {
color: orange;
}
.crimson {
color: crimson;
}
Everything will work as it should and as a bonus it will be easier to manage styles and and you won't have to fix JS code for this.
Make a function
NOTE IDs need to be unique
const scoreColor = score => {
const color = "crimson"
if (score >= 70) return "deepskyblue"; //good movie
if (score >= 50) return "orange"; //not bad
return score;
};
function AddItemsToTable(name, score, img, id) {
const movies = `<div class="content">
<img src="${img}" >
<p>${name}</p>
<p><i class="fa fa-star"></i> <a class="${scoreColor(score)}">${score}</a></p>
</div>`;
body.innerHTML += movies;
body2.innerHTML += movies;
}

How to change a badge color depending on the value it is showing

I'm designing the front-end part of a website using HTML, Bootstrap 3 and jQuery. I want to change the color of a badge depending on the value it was (it will take the value from a database in the future, for now it's on the HTML), but it isn't working right now.
I have this on my HTML file
<span class="badge" id = "rating" onload="ratingColor()">Rating: 0/10</span>
And this on my js file
function ratingColor() {
var a=document.getElementsById("rating");
var num=a.charAt(8);
if(num<5){
a.className ="badge badge-error";
}
else if(num<7 && num>5){
a.className ="badge badge-warning";
}
else{
a.className ="badge badge-success";
}
}
Why is it not working? It just keeps its grey color. Thank you!
Put the onload in a body element, and wrap your element in it.
ratingColor = () => {
let el = document.getElementById("rating");
let num = el.innerText.match(/Rating: ([0-9]+)\//)[1];
if (num < 5) {
el.className = "badge badge-error";
} else if (num < 7 && num > 5) {
el.className = "badge badge-warning";
} else {
el.className = "badge badge-success";
}
}
<body onload="ratingColor()">
<span class="badge" id="rating">Rating: 3/10</span>
</body>
Or, alternatively, if you need the onload applied to only the <span/> element, you may do:
ratingColor = () => {
let el = document.getElementById("rating");
let num = el.innerText.match(/Rating: ([0-9]+)\//)[1];
if (num < 5) {
el.className = "badge badge-error";
} else if (num < 7 && num > 5) {
el.className = "badge badge-warning";
} else {
el.className = "badge badge-success";
}
}
document.getElementById("rating").onload = ratingColor();
<span class="badge" id="rating">Rating: 3/10</span>
Hope that helps,

JQuery crashes after 105 letters

This is a weird one to me. I'm currently creating a multiple choice quiz using js/jquery, and I've found that if I enter a question that is greater than 105 characters in length, the script just doesn't run & no buttons can be clicked.
For example, using the code I've provided this will run absolutely fine and I can have a multiple choice quiz working fine. However, changing the question to a different that is over 105 characters breaks it.
For example, if I changed
"Multiple choice q1"
to
"The process ‘PopularScreenSavers.exe’ is running in the background of a user's laptop. What could this be an example of? " (a question I want to include)
essentially stops my script from running at all.
Included below is the current js as well as a snippet of the relevant html body. It all works perfectly fine... except when I want a longer question.
Any help would be appreciated.
CODE
(function() {
const myQuestions = [
{
question: "The process ‘PopularScreenSavers.exe’ is running in the background of a user's laptop. What could this be an example of? ",
answers:
{
a: "a",
b: "b",
c: "c",
d: "d"
},
correctAnswer: "a"
},
{
question: "Multiple choice q1",
answers:
{
a: "",
b: "",
c: "",
d: ""
}
}];
function buildQuiz()
{
const output = [];
myQuestions.forEach((currentQuestion, questionNumber) =>
{
const answers = [];
for (letter in currentQuestion.answers)
{
answers.push(`<label>
<input type="radio" name="question${questionNumber}" value="${letter}">
${letter} :
${currentQuestion.answers[letter]}
</label>`);
}
output.push(`<div class="slide">
<div class="question"> ${currentQuestion.question} </div>
<div class="answers"> ${answers.join("")} </div>
</div>`);
});
quizContainer.innerHTML = output.join("");
}
function showResults()
{
const answerContainers = quizContainer.querySelectorAll(".answers");
let numCorrect = 0;
myQuestions.forEach((currentQuestion, questionNumber) =>
{
const answerContainer = answerContainers[questionNumber];
const selector = `input[name=question${questionNumber}]:checked`;
const userAnswer = (answerContainer.querySelector(selector) ||
{}).value;
if (userAnswer === currentQuestion.correctAnswer)
{
numCorrect++;
answerContainers[questionNumber].style.color = "#009A44";
answerContainers[questionNumber].style.fontWeight = "900";
}
else
{
answerContainers[questionNumber].style.color = "#DA291C";
answerContainers[questionNumber].style.fontWeight = "900";
}
});
resultsContainer.innerHTML = `${numCorrect} out of ${myQuestions.length}`;
}
function showSlide(n)
{
slides[currentSlide].classList.remove("active-slide");
slides[n].classList.add("active-slide");
currentSlide = n;
if (currentSlide === 0)
{
previousButton.style.display = "none";
}
else
{
previousButton.style.display = "inline-block";
}
if (currentSlide === slides.length - 1)
{
nextButton.style.display = "none";
submitButton.style.display = "inline-block";
}
else
{
nextButton.style.display = "inline-block";
submitButton.style.display = "none";
}
}
function showNextSlide()
{
showSlide(currentSlide + 1);
}
function showPreviousSlide()
{
showSlide(currentSlide - 1);
}
const quizContainer = document.getElementById("quiz");
const resultsContainer = document.getElementById("results");
const submitButton = document.getElementById("submit");
buildQuiz();
const previousButton = document.getElementById("previous");
const nextButton = document.getElementById("next");
const slides = document.querySelectorAll(".slide");
let currentSlide = 0;
showSlide(0);
submitButton.addEventListener("click", showResults);
previousButton.addEventListener("click", showPreviousSlide);
nextButton.addEventListener("click", showNextSlide);
})();
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<div class="quiz-container">
<div id="quiz"></div>
</div>
<button id="previous">Previous Question</button>
<button id="next">Next Question</button>
<button id="submit">Submit Quiz</button>
<div id="results"></div>
Edit: adding that this runs as valid js, but it doesn't run in Chrome - should have specified, apologies.
jsfiddle
These fiddles should show the issues I'm having:
Working - https://jsfiddle.net/3m5afcuo/
Not working (only change made was to the string) - https://jsfiddle.net/su3hptdq/

Categories

Resources