Tips for concealing a complete class without causing any issues

My attempt at creating a quiz feature has been a challenge. I wanted each section of the quiz to open as I move through the questions. Here are the initial two parts of the quiz.

function initialize() {
  var section = document.getElementsByClassName("part2")
  var index = 0
  while (section.length >= index) {
    section[index].style.visibility = "visible";
    index += 1;
  }
  return section
}
    function question1Correct(){
        document.getElementById("q1correctwrong").innerHTML="yes!"
    
        
    }
    function question1Wrong(){
        document.getElementById("q1correctwrong").innerHTML="no"
    }
.part2{
        visibility: collapse;
    }
<part1 class="part1">
  <h1 style="text-align: center" class="part1">Hello!</h1>
  This is a test. No pressure. Ok! Have fun!
  <div class="part1"></div>
  <button class="part1" onclick="initialize()">Begin!</button>
  <div class="part1"></div>
</part1>
<part2 class="part2">
  1+1=?
  <div class="part2"></div>
  <button class="part2" onclick="question1Wrong()">1</button>
  <button class="part2" onclick="question1Correct()">2</button>
  <p class="part2" id="q1correctwrong"></p>
</part2>

Although it is functional, there are some errors being thrown:

{ "message": "Uncaught TypeError: Cannot read property 'style' of undefined", "filename": "https://stacksnippets.net/js", "lineno": 31, "colno": 11 }
How does it function and what is causing these errors?

Answer №1

Modify

for (var x = 0; x < b.length; x++ ) {
    b[x].style.visibility = "visible";
  }

Into

for (var x = 0; x < b.length; x++ ) {
    b[x].style.visibility = "visible";
  }

Snippet 1

function start() {
  var b = document.querySelectorAll(".part2")
  for (var x = 0; x < b.length; x++ ) {
    b[x].style.visibility = "visible";
  }
  return b
}
    function q1nextcorrect(){
        document.getElementById("q1correctwrong").innerHTML="yes!"
    
        
    }
    function q1nextwrong(){
        document.getElementById("q1correctwrong").innerHTML="no"
    }
.part2{
        visibility: collapse;
    }
<part1 class="part1">
  <h1 style="text-align: center" class="part1">Hello!</h1>
  This is a test. No pressure. Ok! Have fun!
  <div class="part1"></div>
  <button class="part1" onclick="start()">Begin!</button>
  <div class="part1"></div>
</part1>
<part2 class="part2">
  1+1=?
  <div class="part2"></div>
  <button class="part2" onclick="q1nextwrong()">1</button>
  <button class="part2" onclick="q1nextcorrect()">2</button>
  <p class="part2" id="q1correctwrong"></p>
</part2>

Snippet 2: Simplified version

document.querySelector("[beginN]").addEventListener("click", start);
function start() {
  var b = document.querySelector(".p2");
  b.classList.toggle("d-none");
}
const answers = document.querySelector("#answers");
const a = answers.querySelectorAll("button");

for(var x = 0; x < a.length; x++){
  a[x].addEventListener("click", function(){
    if(this.getAttribute("val") == 2)
      document.getElementById("result").innerHTML = "Hooray!";
    else
      document.getElementById("result").innerHTML = "Failed!";

  });
}
.d-none{ display:none; }
<div class="p1">
  <h1 style="text-align: center">Hello!</h1>
    This is a test. No pressure. Ok! Have fun!
    <button beginN>Begin!</button>
</div>
<div class="p2 d-none">
  1 + 1 = ? <br>
  <div id=answers>
  ? =
          <button val="1">1</button>
          <button val="2">2</button>
      </div>
  <p id=result></p>
</div>

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

CSS :hover activates only when the mouse is in motion

Looking at a simple example I put together: HTML <div id="sample"></div> CSS #sample { width:400px; height:400px; background-color:green; display:none; } #sample:hover{ background-color:red; } It's a hidden DIV tha ...

Using React-Router v6 to pass parameters with React

My App.js file contains all the Routes declarations: function App() { return ( <div className="App"> <Routes> <Route path="/"> <Route index element={<Homepage />} /> ...

Implementing Dynamic Weight-based Pricing with CodeIgniter and AJAX

My shopping cart website utilizes ajax and Codeigniter to add products without reloading the page. Originally, I displayed a single net weight for each product. However, I recently switched to multiple net weights for the same product. Unfortunately, I am ...

Incorporate a dynamic fading effect for text and images using JQuery

I successfully implemented a Crossfade effect using Jquery: function doAnimationLoop(o, n, t, i, a) { fadeInOut(o, n, t, i, function() { setTimeout(function() { doAnimationLoop(o, n, t, i, a) }, a) ...

Trigger the select dropdown when a key is clicked

I am currently working on a project in react where I am utilizing the Select component from material. When I open the dropdown and press a key on my keyboard, the option starting with that key gets automatically selected. This behavior is also observed in ...

Having a problem with file uploads in node.js using multer. The variables req.file and req.files are always coming

I am encountering an issue with uploading a file to my server, as both req.file and req.files are consistently undefined on my POST REST endpoint. The file I'm attempting to upload is a ".dat" file, and my expectation is to receive a JSON response. ...

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...

What could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

The Context API leaves me feeling lost and confused

I am currently utilizing Auth0 for user sign up. My goal is to extract the user id listed under sub:value, and then add it to my database to associate it with a user's post. To achieve this, I am attempting to utilize a Context API to retrieve the use ...

Can you explain the process that takes place when require("http").Server() is called with an Express application passed in as a parameter?

As I was exploring the Socket.io Chat Demo found at this link: http://socket.io/get-started/chat/, I came across their require statements which left me feeling confused. var app = require('express')(); var http = require('http').Server ...

Increase the bottom padding or add some extra space to the Bootstrap form or page

I am currently working on enhancing a Bootstrap Form that includes reset/submit buttons positioned at the bottom. A common issue is when iPhone users attempt to click the Submit button, which initially displays Safari icons before requiring an extra tap to ...

Tips for creating a sticky bootstrap column that remains in place as you scroll

I am looking to design a FAQ page similar to Twitter's FAQ. The goal is to have the left column remain fixed in its position while allowing users to scroll through the content. Here is what I have attempted so far, but it is not functioning as expect ...

The CSS header remains the same size regardless of the size of the dynamic table

Is there a way to set the header in an XHTML page to be as wide as the page itself? I used width:100%, but the issue is that I have a dynamic table and when it grows bigger, the header doesn't expand. How can I solve this problem? #header{ top: 0 ...

Ensuring the presence of Objects/Functions in different browsers using javascript

I am seeking advice on the best practices for testing object existence for cross-browser compatibility. There are numerous methods available for testing whether an object/function/attribute exists. While I could utilize jQuery or another library, my prefe ...

The label is not displaying the specified font-family in CSS

Below is a snippet of code that I am having trouble with: testing some content Additionally, here is the CSS code for it: label { font-family: "Andale Mono"; } The issue I am facing is that no matter which font style I try to apply, it does not seem to ...

Are you familiar with using double conditional rendering in a React application?

Currently, I am in the process of creating a small clothing store application using React as a way to expand my skills. One feature I have implemented is a filter by price section. However, I am looking for a solution to handle cases where no items fall wi ...

Is it possible to configure the async.retry method to retry even upon successful queries, depending on a specific condition?

Currently, I am delving into the node.js async module and wondering if it's possible to modify the behavior of the async.retry method. Specifically, I'd like it to retry even on successful operations but halt based on a certain condition or respo ...

Trouble arises as the Raspberry Pi GPIO pins refuse to toggle

Encountering an intriguing issue here. I've developed a Python program to regulate the climate of a room with a web interface. While the program functions properly, upon restarting the Raspberry Pi, all GPIO pins are activated. It's only after ac ...

steps to invoke a class within a function

I'm currently attempting to invoke a model class from the Axios response. Instead of displaying an alert, I would like to show a modal popup. Can someone assist me with how to call the modal class from the Axios interceptor function? Thank you in adva ...

Adjust the Material UI Select component to accommodate the length of the label

Is there a way to automatically adjust the size of Material-UI's Select input based on the label? In the official demo, minWidth is added to the formControl element. However, I have multiple inputs and do not want to set fixed sizes for each one. Whe ...