Tips for concealing the preceding list item using jQuery

I am currently working on a project that involves a ul tag with 5 li items.

My goal is to display each item one by one when a button is clicked. This would mean showing the next item and hiding the previous one, similar to what happens in quizzes.

Here is the HTML code I am using:

<div class="span12" style="margin-top:140px;">
<ul id="part">
<li id="div0" style="display:none;">Question 1</li>
<li id="div1" style="display:none;">Question 2</li>
<li id="div3" style="display:none;">Question 3</li>
<li id="div4" style="display:none;">Question 4</li>
<li id="div5" style="display:none;">Question 5</li>
</ul>
<button id="next">Next</button>
</div>

And here is the jQuery code:

<script>
$(function(){
    var items = $('ul#part li');
    if(items.filter(':visible').length == 0)
    {
        items.first().show();
    }
    $('#next').click(function(e){
        e.preventDefault();
    items.filter(':visible:last').next().show();
    });
});
</script>

While this code allows me to show the next item on button click, I am having trouble hiding the previous item.

How can I hide the previous item when clicking on "Next"?

Your assistance would be greatly appreciated.

Answer №1

This code snippet is ready to go

<script>
$(function(){
    var elements = $('ul#part li');
    if(elements.filter(':visible').length === 0){
        elements.eq(0).show();
    }

    $('#next').on('click', function(event){
        event.preventDefault();

        var activeItem = elements.filter(':visible:last');
        activeItem.hide();

        var nextItem = activeItem.next();
        if (nextItem.length > 0)
             nextItem.show();
    });
});
</script>

Remember, checking the length of an element helps you determine its existence.

Answer №2

Building on Arek's response, update the if statement to:

if (next.length) {
  next.show();
} else {
  $('#next').html("Submit");
}

This will change the button text to "Submit."

Check out the live example on Fiddle

Answer №3

Let's create a global variable named "index" to keep track of our current position in the array of items.

('#next').click(function(e) {
      e.preventDefault();
      items.hide();
      items[index].show();
      index == items.length - 1 ? index = 0 : index++;
 });

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

Adjusting font sizes for both multiline text within a <p> element and labels based on the number of lines

Whenever I have multiline paragraphs or labels, the font size seems to adjust depending on the number of lines. All I want is to keep the font size consistent regardless of the lines. The labels all have the same CSS styling and inheritance. Here is a vis ...

The Microsoft Booking feature is not being shown in the iframe

https://i.sstatic.net/QYNGI.png Instead of the booking website, this is what is being displayed. Below is the code snippet: index.js import React from 'react' const Appointment = () => { return ( <iframe src='https://outlook ...

What is the technique for rearranging columns to be at the top in Foundation for mobile devices?

On my desktop, I have a layout like this: [Column1 large-8] [Column2 large-4] For mobile view, I'd like it to be like this: [Column2 large-4] [Column1 large-8] Below is the code snippet I am working with: <div id="search-content" class="row ma ...

There was an uncaught error in AngularJS stating that the URL in the HTTP request configuration must be a string

I've been working on a web application and have encountered some challenges. One particular issue I'm struggling with is related to the following code snippet: this.bookSpace = function (date, spaceId) { swal({ title: "Are you sure?", t ...

Ways to determine if a website is being accessed from a mobile device or a computer without relying on TeraWurfl technology

After my search on the internet yielded no answers, I decided to post my question here. Is there a method available to detect whether a site is being accessed from a computer or mobile device without using TeraWurfl? I'm looking for a simple code snip ...

Deciphering a JSON response obtained from a jQuery output within a PHP context

I have created a simple search form that uses jQuery to query an external server for results. $("#formsearch").on("submit", function (event) { // all good! event.preventDefault(); submitFormSearch(); }); function submitFormSearch() ...

Do you have any suggestions on how to fix this npm SQLite installation issue?

Could use some help with an SQLite installation error I'm encountering. Any ideas on what the issue might be and how to resolve it? C:\Users\jacka\Downloads\discord-emoji-stealer-master\discord-emoji-stealer-master>npm i & ...

I've been attempting to relocate a CSS element at my command using a button, but my previous attempts using offset and onclick were unsuccessful

I am trying to dynamically move CSS items based on user input or button clicks. Specifically, I want to increment the position of elements by a specified number of pixels or a percentage of pixels. Currently, I am able to set the starting positions (top a ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

Steps for adjusting button size in Sencha Touch

How can I resize a button in Sencha Touch 2 to make it smaller? I need to change its height. Any sample code you could provide would be greatly appreciated! Thanks navigationBar: { items:[{ xtype: 'button', ...

How to dynamically update the selected options based on different content within a single-page app using jQuery Mobile

We are currently working on a hybrid application and have a requirement where the user can select an option, and based on the selection, we need to display different content. For example, if the user selects India, US, or Canada: - If India is selected, o ...

Guide to creating a dynamic illumination using CSS, HTML, and JS

Can you help me create a unique lighting effect for a specific section of my webpage? I'm curious about the techniques needed to achieve a similar effect as seen on another webpage. Is it feasible to create this effect using only CSS and HTML, or are ...

The output displayed is showing the result of an Ajax request as `[object HTML

When I attempt to retrieve data using ajax, the output displays as [object HTMLInputElement]. Is there a way to convert this object to a string? Below is my JSP code which utilizes ajax: $('select#product').change(function() { var para ...

Sending an Ajax request using a dropdown menu

I'm having trouble retrieving a value from my database when a select option is chosen. The select options are generated dynamically from the same database. As a beginner in AJAX requests, I am struggling to figure out why I am only getting a blank re ...

"Ensure that the jspdf header is configured to display on every page

Currently, I am integrating jspdf code with a jQuery script and the jspdf.debug.js file. My HTML table (angular ng-repeat) is very large and spans multiple pages. While jspdf does a great job repeating the header of the table nicely, I have some invoice in ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...

Adjust the size of a menu by modifying its width

Hey everyone, I recently joined this website and I'm still learning how to code. My current project involves creating an off-canvas menu, but I've come across a few challenges. Firstly, does anyone know how to adjust the width of the menu when it ...

Is there a way to assign a dynamic value to an input just once, and then retain the updated value without it changing again

During a for loop, I have an input element (type number) that needs its value modified by decrease and increase buttons: <div class="s-featured-list__item s-featured-list__item--expandable" v-for="(item, itemIndex) in category.items" ...

Why is the value of the form's select element always null in jQuery?

I have completed this task multiple times without any issues, but I seem to be facing a problem now. Whenever I make a selection from the dropdown list, the .value always returns null, which is puzzling as I know this should not be the case. Can anyone spo ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...