JavaScript code for displaying div elements

How can I use script code to show different divs when a button is clicked?

This is my current progress:

'''

<head>
    <style>
        #div-1, #div-2, #div-3{
          display: none;
          width: 100%;
          padding: 50px 0;
          text-align: center;
          background-color: lightblue;
          margin-top: 20px;
        }
    </style>
</head>

<body>
<form>
    <input type="text" id="number" value="0"/>
</form>
<p>What is the color of the ocean?</p>
<div id="div-1">
    <p>What is the color of the sky?</p>
</div>
<div id="div-2">
    <p>What is the color of the sand?</p>
</div>
<div id="div-3">
    <p>What is the color of the bus?</p>
</div>


<button onclick="nextQuestion()">Next Question</button>

<script>
function nextQuestion()
{

}
</script>

'''

Answer №1

Keep track of the current element being displayed, and increment its index by +1 after each click:

let elements = document.querySelectorAll(".question");
let currentIndex = 0;

show(elements[currentIndex]);

document.getElementById("next").addEventListener("click", function _tmp() {
  hide(elements[currentIndex]);
  currentIndex++;
  
  if( !elements[currentIndex] ) {
    this.removeEventListener("click", _tmp);
    this.textContent = "No more questions!";
    // 'this' keyword refers to the context of the function call (in this case: The clicked button)
    return;
  }
  
  show(elements[currentIndex]);
});

/***/
function show(el, value) {
  el.style.display = value || "block";
}
function hide(el) {
  el.style.display = "none";
}
.question {
  display: none;
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
<button id="next">Next Question</button>
<hr>

<div class="question">
  <p>What is the color of the ocean?</p>
</div>
<div class="question">
  <p>What is the color of the sky?</p>
</div>
<div class="question">
  <p>What is the color of the sand?</p>
</div>
<div class="question">
  <p>What is the color of the bus?</p>
</div>

By the way, if you see specific ids, class names, variables, etc. in your code, that may indicate an issue) Try to approach the problem in a more generalized manner using loops and arrays.

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

The translation of popups using ngx-translate in Javascript is not functioning properly

When I click on my request, the content "Are you sure?" is not changing to the required language. This issue is located in list.component.html <button type="button" (click)="myrequest(item.Id)">Request View</button> The fu ...

Unable to retrieve the 'href' on different pages

Why am I unable to retrieve the "href" from other pages, but still can on the first page? Is there something wrong with it? Will changing the Xpath allow me to get all "href"s from every page? !pip install selenium from selenium import webdriver import t ...

Should we consider the implementation of private methods in Javascript to be beneficial?

During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option. Two alternatives were discussed: Using a constructor and prototype containing all functions, where non-API meth ...

When URL string parameters are sent to an MVC controller action, they are received as null values

Are You Using a Controller? public class MyController : Controller { [HttpGet] public ActionResult MyAction(int iMode, string strSearch) { return View(); } } Within my view, I have a specific div with the id of "center" I am runn ...

Making a full-width browser bar by utilizing negative margins

I've been following a tutorial and need help with my header element. I want it to have a max-width of 800px and be centered in the middle of the page. Inside the header, there will be a #filtersBar div that spans the entire width of the page. Here&apo ...

Using Kendo Grid to Transfer Data Between Grid Cells

Recently, I encountered a problem in my Kendo MVC project where I needed to drag a product code from one Kendo Grid to another when the cell value was empty. Here's the scenario: Grid A contains products ordered, but the vendor sending the list has i ...

What is the best way to transfer information from node.js to HTML?

This is a sample code in Node.js var http = require('http'); var request = require("request"); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!& ...

Arrange two <p> elements in a horizontal alignment

How can I align two <p> elements on the same line? I am trying to align both <p> elements on the same line, one to the left and the other to the right. <p style="text-align:left">Copyright &copy; {$date_year} {$companyname}. All R ...

Ul list centered alignment appears misaligned to the left in Safari browser exclusively

I'm experiencing an issue with my menu alignment. It appears perfectly centered in FF, Chrome, and IE, but shifts to the left in the Safari browser. I'm not sure if there is a specific CSS property I need to use to correct this alignment. <d ...

Is there a way to connect an HTML page without using a hyperlink?

Is there a way to directly display linked HTML pages on my webpage instead of just creating a link? I'm looking for suggestions on how to arrange this. Thank you! ...

How can I iterate over an array in JavaScript to create posts for an HTML feed using Bootstrap?

I have created a simple Bootstrap website in HTML that resembles a news feed. To populate the feed with various posts, I am using Javascript to work with arrays containing images, headlines, and captions for each post. My initial approach involves looping ...

How the logo's placement shifts while zooming out (using CSS and Angular 4+)

I am facing an issue with my navbar that includes a logo (MostafaOmar) which shifts position when zoomed out. If you try zooming to 70%, you will notice the logo's position changes as well. Is there a way to make it stay in place at 100% zoom? Here ...

Problem encountered with Firefox when using jQuery's hide() function

I am facing an issue with the hide() function in a project I am working on. The selected div layer is not hiding as expected. Everything seems to be functioning correctly in Safari and Chrome, but unfortunately, it is not working in Firefox :-( You can v ...

What is the best way to combine two JavaScript functions into a single function, especially when the selector and function to be invoked may differ?

In the provided snippet, I am using the following function callers: // del if ( maxDelivery > 0 ) { if ( maxDelivery === 1 ){ delAdressFunc( dels ); } else { for ( i = 0; i < maxDelivery; i += 1 ){ delAdressFunc( ...

Identifying a shift in data model within a component

It seems like there's a piece I might be overlooking, but here's my current situation - I have data that is being linked to the ngModel input of a component, like so: Typescript: SomeData = { SomeValue: 'bar' } Snippet from the vie ...

Variability in the console output upon shutting down the express server

As part of a university module, I am currently developing a Node/Express web application. The structure of my project includes three main files: db.js, app.js, and entry.js. The db.js file is responsible for creating a Sequelize instance and exporting it ...

What is the best way to invoke the update() and ScrollTop() methods in Angular for ngx-perfect-scrollbar?

Currently, I am utilizing the "ngx-perfect-scrollbar": "^5.3.5" library in my project. I have implemented a feature to toggle between "See More" and "See Less", however, when these actions are triggered, the Perfect Scrollbar does not update itself prope ...

Issue with Saving Modal in Bootstrap 5: Button Does Not Function

I've been following the instructions on , but I'm facing an issue with getting the save button to work on my modal. Initially, I tried placing it within the form tag, but it ended up using the form action from the main view instead of the partial ...

The PHP script is saving unpredictable data in the database

I've been struggling to figure out why my added fields aren't being stored properly in the database. After extensive investigation, I've determined that jQuery is not adding HTML fields correctly, which is preventing them from being submitte ...

Which specific file name patterns does npm publish consistently exclude?

When using the npm publish command, the documentation mentions that certain files will not be included in the package unless explicitly added to the "files" list in package.json or un-ignored with a specific rule. What exactly are these "certain patterns"? ...