I am developing a quiz application using JavaScript, and I am wondering how I can smoothly transition from one question to the

I'm working on developing a quiz application and I'm facing an issue where my quiz is skipping question 2 when moving from one question to the next using the "next" button. I have a total of 3 questions in my quiz and for some reason, it jumps from question 1 to question 3 without displaying question 2. I would greatly appreciate any assistance or tips on how to fix this problem. You can view my code on CodePen via the following link: https://codepen.io/Michaelm4100/pen/GRQxNQO?editors=1011

// Function to toggle active-question class for each question 
function activeQuestion(el) {
   var que = document.getElementsByClassName('question');

    for (var questions of que) {
      // console.log(questions)
      
      // Remove active-question class 
      questions.classList.remove('active-question');
    }
    questions.classList.add('active-question');
}


var nextButton = document.getElementsByClassName('nxt-btn'); 


for (var buttons of nextButton) 
  
  buttons.addEventListener('click', function(e){
    // Call the active Question function on button click event 
    activeQuestion(e);
  })
}

Answer №1

When looping through elements using var questions of que, the final value of questions will be the last element. This means that if you try to add a class with

questions.classList.add('active-question')
after the loop, it will always target the final element.

To fix this issue, maintain an index variable to keep track of the active question at any given time.

const questions = document.querySelectorAll('.question');
let activeQuestionIndex = 0;
for (const nextButton of document.getElementsByClassName('nxt-btn')) {
    nextButton.addEventListener('click', () => {
        questions[activeQuestionIndex].classList.remove('active-question');
        activeQuestionIndex++;
        questions[activeQuestionIndex]?.classList.add('active-question');
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using javascript to generate fresh dictionaries

Struggling to translate a C# "function" into JavaScript - any advice or tips? Here is the C# snippet: var parameters = new Dictionary<string,string> { { "link", "http://mysite.com" }, { "name", "This is an test" } }; I believe I need to ut ...

Guide to showcasing a placeholder in MUI's Select component

How can I add the placeholder "Select a brand" to this select element? I've tried different options with no luck. Here is the code snippet I am working with: <FormControl fullWidth> <InputLabel id="demo-multiple-name-label" ...

Implementing the onClick function for the correct functionality in a ReactJS map component

I have designed a mockup and now I am trying to bring it to life by creating a real component. View my component mockup here Starting with something simple, I created 3 buttons and an array. However, when I click on any button, all features are displayed ...

Nunjucks not loading the script when moving from one page to another

Currently, I am in the process of developing a website utilizing nunjucks and express. This website serves as a blog platform with content sourced from prismic. My goal is to load a script file for an active campaign form whenever a user navigates from a b ...

What is the best way to showcase an item from an array using a timer?

I'm currently working on a music app and I have a specific requirement to showcase content from an array object based on a start and duration time. Here's a sample of the data structure: [ { id: 1, content: 'hello how are you', start: 0 ...

Steps to successfully click a button once the popup window has finished loading entirely

Is there a way to programmatically click on an HTML element? I am currently using JQuery selectors to identify a button and then trigger a click event. $('span.firstBtn').click(); Once this button is clicked, a popup window appears. How can I w ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

I'm not sure if I'm doing this right, the image seems to be overlapping the border

Just dipping my toes into the world of HTML/CSS, so feel free to point out any major errors in my code. The issue I'm facing is illustrated in this image (Apologies for the black boxes covering up some content; focus is on the top image). Check out ...

The sequence of CSS and deferred JavaScript execution in web development

Consider this scenario: you have a webpage with a common structure in the <head>: <link rel="stylesheet" href="styles.css"> // large CSS bundle <script defer src="main.js"></script> // small JS bundle with defer attribute There is ...

Determining the scrollWidth of a div with an absolutely positioned child div

Having some trouble determining the width of a div's content instead of the div itself. The typical solution would involve using Javascript's scrollWidth property. However, there is a complication in this case. Inside the div, another div is ab ...

How to perfectly align a button at the center and position it in the forefront?

I'm attempting to place a button in front of my video and center it on the video. I've tried using position-relative to bring it in front and flex to center it vertically and horizontally, but it's not working as expected. The z-index is cor ...

Issue with Bootstrap dropdown menu not showing up/functioning

I've spent the entire day trying to find a solution and experimenting with various methods, but I'm still unable to get it to work. The navbar-toggle (hamburger menu) shows up when the window is resized, but clicking on the button doesn't di ...

Issue with Javascript form submission leading to incorrect outcomes

When setting the form action to a text retrieved from the database with an ID, I encountered a problem where it always displays the first ID even when clicking on text holding ID=2. Upon checking the page source, the correct IDs are shown for all texts. B ...

One way to send image data from the front end to the back end using AJAX

Client-Side JavaScript: var userInfo = { 'username': $('#addUser fieldset input#inputUserName').val(), 'email': $('#addUser fieldset input#inputUserEmail').val(), 'fullname': $('#addUser f ...

Position a component in relation to another component using AngularJS

Utilizing ng-show and ng-hide, I created a descriptive box that appears below text when clicked. However, there is an issue as the description box does not align directly under the text, similar to what is shown in this image https://i.stack.imgur.com/phBh ...

Attempting to craft a multi-filter feature using AngularJS that will allow for the precise filtering of JSON data based on both month and year identifiers

I have integrated AngularJS into the RoR framework and am working on creating a multi-filter for the "ng-repeat" function to filter JSON data based on "month_id" and "year_id". Here is the current code: JSON: [ { "date":"October 4, ...

Is there a way to resolve this issue? (An error occurred: TypeError - res.json is not a valid function)

When attempting to add an object to my MongoDB database const response = await fetch("/api/contact", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); I encounter the error message ...

What are the best practices for storing an array of objects in MongoDB with Mongoose?

For my project, I needed to store data in a mongoDB document as an array of objects using Javascript, Node JS, Express framework, and Mongoose library. After researching online, I found two different methods to achieve this: Creating another sub-schema ...

The functionality of the delete button in Material UI Chip seems to be malfunctioning

I am working on mapping Material UI Chips, but I am facing an issue where the cross button is not showing up and I cannot click on them or use the onTouchTap event. Below is my mapping: {mapping.map(chipMap => { return ( <div> ...

Animating with React JS using JSON data sources

Currently, my project involves using React/Redux to store animation data in JSON and display it on a React page. The challenge lies in implementing the animations correctly while utilizing setTimeout for pauses and setInterval for movement. The Animation ...