showcasing a set of div elements by using forward and backward buttons

I am dealing with 5 divs that have text content inside.

To navigate through each div, I have implemented a back and next button system.

<a href="" class="back-btn off">Back</a> | <a href="" class="next-btn">Next</a>

<div class="vote-result first">
  This is an example text
</div>

<div class="vote-result">
  Here is some more text
</div>

<div class="vote-result">
  More text to read
</div>

<div class="vote-result">
  This is the final section of text
</div>

// Hiding all divs except for the first one initially.

.vote-result { display: none; }
.vote-result.first { display: block; }

On the first click of the next button, I want to remove the 'off' class to make it clickable. Initially, the link should be disabled and later re-enabled.

$(".back-btn").removeClass("off");

When the last div is reached, I need to add the 'off' class to the next-btn to disable it.

Although I considered using a carousel JavaScript plugin for this functionality, I feel it's unnecessary at the moment.

I have thought about a solution involving sub-classes for the links based on which button was clicked (back or next), to determine which div should be displayed next and manage the state of the buttons accordingly.

I would like to find a way to incorporate additional divs without having to modify the existing code. Any suggestions are welcome, thank you.

Answer №1

Here is a solution tailored just for you. Feel free to check out the Fiddle I created based on your requirements.

Below are snippets of code:

<a class="back-btn off">Back</a> | <a class="next-btn">Next</a>

<div class="vote-result first selectedDiv">
  this is an example snippet
</div>

<div class="vote-result">
  more content here
</div>

<div class="vote-result">
  additional copy goes here
</div>

<div class="vote-result last">
  this marks the final section
</div>

For JS/jQuery functionality, refer to the following code:

$(".back-btn").click(function(){debugger;
    var prevElement=$('.selectedDiv').prev();
    prevElement.show();
    $(".selectedDiv").hide();                         
    $(".selectedDiv").removeClass("selectedDiv");
    prevElement.addClass("selectedDiv");                            

   if($('.first').css('display')=="block"){
       $(".back-btn").addClass("off");
   }
   else{
    $(".next-btn").removeClass("off");  
   }
});

$(".next-btn").click(function(){debugger;
    var nextElement= $('.selectedDiv').next();
    nextElement.show();
    $(".selectedDiv").hide();                         
    $(".selectedDiv").removeClass("selectedDiv");
    nextElement.addClass("selectedDiv");
    if($('.last').css('display')=="block"){
      $(".next-btn").addClass("off");
   }
   else{
     $(".back-btn").removeClass("off");  
   }
});

The CSS code snippet is as follows:

.vote-result { display: none; }
.vote-result.first { display: block; }
.off{display:none;}

Answer №2

Your New HTML Code:

<html>
    <head>
        <style>
            .vote-result { display: none; }
            .vote-result.first { display: block; }
            .off {
                color: Red;
            }
            a {
                color: blue;
            }
        </style>
        <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
        <script src="code.js"></script>
    </head>
    <body>
        <a href="" class="back-btn off">Back</a> | <a href="" class="next-btn">Next</a>

        <div class="vote-result first">
          This is an example of text
        </div>

        <div class="vote-result">
          This is some additional text content
        </div>

        <div class="vote-result">
          More text content goes here
        </div>

        <div class="vote-result">
          This is the final div block
        </div>
    </body>
</html>

Update to your "code.js" file in the same directory:

/**
 * The current index (starting from zero) of the displayed <div class="vote-result"> element
 * @var {Number}
 */
var activeIndex = 0;

function getNumberOfItems() {
    return $('.vote-result').length;
}

function synchronizeInterface() {
    var numberOfItems = getNumberOfItems(),
        lastIndex = numberOfItems - 1;

    $('.vote-result').removeClass('first');
    $('.vote-result').each(function(index) {
        if (index == activeIndex) {
            $(this).addClass('first');
        }
    })

    $('.back-btn').toggleClass('off', activeIndex == 0);
    $('.next-btn').toggleClass('off', activeIndex == lastIndex);
}

$(function() {
    $('.back-btn,.next-btn').on('click', function() {
        // Check if the clicked button is enabled
        if (!$(this).hasClass('off')) {
            // Determine if "Next" or "Back" button was clicked
            var clickedNext = $(this).hasClass('next-btn');

            // Update the active index based on button clicked
            activeIndex = clickedNext
                ? Math.min(activeIndex + 1, getNumberOfItems() - 1)
                : activeIndex = Math.max(0, activeIndex - 1);

            // Update the interface with new variables
            synchronizeInterface();
        }

        return false;
    });
});

Note: There was an issue with a missing double-quote in one of your class attributes in HTML code. Additionally, I added more styling and suggested renaming ".first" class to ".active".

Answer №3

Explore the capabilities of jQuery's .next() method for easy navigation - jQuery - Next(). You can also use this simple check to determine if an element is the last one in a sequence.

if($(this).is(':last-child'))
{
    $('.next-btn').removeClass('off');
}else{
    $('.next-btn').addClass('off');
}

Make sure to apply this logic whenever a navigation button is clicked, including handling the first button accordingly.

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

extracting URL parameters using AJAX

I have successfully created an AJAX request using the GET method, passing variables to the URL and receiving a response. Now, I need to retrieve the current URL variables by clicking on a newly created button in order to proceed with further processing. Th ...

In my opinion, CSS3 transform translateZ can be likened to scaling in some way

There are instances where I believe that the translateZ and scale properties produce similar effects, akin to zooming in or out. I suspect there is a mathematical relationship between them. If I know the value of one, such as translateZ(-1000px), along wi ...

The infinite scroll feature on Next.js resulted in duplicating the last element during the initial fetch process

I have a project that involves fetching data from Strapi Rest API using Next.js. I am fetching and displaying cards based on the fetched content. To prevent loading all the data at once, I have implemented an infinite scroll feature using react-infinite-sc ...

Connect an existing function to JQuery animation

There is a function in place that changes the background image of a vertical website when a navigation menu item is clicked. <script type="text/javascript"> $(function() { $('a.panel-home').click(function(){ $("#bgimg").attr(' ...

Encountering an issue with react-dom that needs to be resolved

After updating my node and npm installations, I encountered an error when trying to run my project. Specifically, I am using "react": "^0.13.3" and "react-dom": "0.14.0-beta3" npm WARN unmet dependency /Users/hilarl/Desktop/client/node_modules/react-do ...

Instruct Smarty to display the block exactly as it is

Struggling to inline some JavaScript code into the Smarty template files due to the {ldelim} {rdelim} markers. Is there a way to instruct Smarty to disregard the markup and just output it as is? Any similar approach like CDATA blocks in XML? Just demonstr ...

In what way can you set the sequence of properties in a JavaScript object for a MongoDB index while using node.js?

The MongoDB documentation emphasizes the importance of the sequence of fields in compound indexes. The definition of an object in ECMAScript states that it is an unordered collection of properties. When using MongoDB with node.js (such as with this mod ...

What is the best way to implement callback functionality within a UI dialog?

I am currently working with two pages: main.aspx and register.aspx. When the register page is loaded within a UI dialog on main.aspx, I encounter issues with callback functions. Main.aspx seems to utilize the register's callback and raisecallback fun ...

A guide to customizing the label color in Material-UI's <TextField/> component

How do I change the text color of the "email" label to match the border color? Below is the provided code: import React, { Component } from "react"; import { Icon } from "semantic-ui-react"; import { Divider } from "semantic-ui-react"; import { TextField ...

Cropping and resizing images

Within my angular application, I have successfully implemented image upload and preview functionality using the following code: HTML: <input type='file' (change)="readUrl($event)"> <img [src]="url"> TS: readUrl(event:any) { if ...

The property linerGradiant of r cannot be destructured because it is not defined

I encountered the error "Cannot destructure property linerGradiant of r as it is undefined" during runtime, making it difficult to debug. The issue seems to stem from the compiled JS file, which is hard to read. The function is defined as follows: functio ...

Exploring Techniques for Streamlining HTML/CSS Editing in Browser

Is there a way to automatically edit specific lines on websites right after they load? Specifically, I want to change <div class="1"> to <div class="1" style="display:none">, and <div class="2" style ...

Position icons and images on the right side, and the textarea on the left side of the page (using Twitter

Summary: Here is the desired end result shown in the image below. Alternatively, you can refer to the JSFiddle. Ideally, only CSS should be used without changing the DOM structure. The icons need to be aligned completely to the right using the .pull-right ...

Include money symbols within input fields with padding and vertical alignment

I am looking to create an input field that includes either € or $ currency symbols. The challenge is ensuring perfect vertical centering inside the input, especially when using padding. Is there a foolproof method to achieve this? https://i.stack.imgur ...

Can pure Javascript be used to integrate Bootstrap pagination into a Bootstrap table?

I have created a custom JavaScript code to generate a Bootstrap table with hardcoded values. Now, I am looking to implement Bootstrap pagination using JavaScript only. var table = document.createElement("table"); table.className = "table"; var the ...

Instructions for sorting an array of objects by Firebase Timestamp

I am looking for a way to order my messages based on timestamp in Firebase v9. In earlier versions, I was able to do this but now I seem to be facing some difficulties. Here is the data structure set up on Firestore: const [messages, setMessages] = useSta ...

What is the best way to utilize scope apply or run functions upon successful completion in Angular 8 jQuery ajax requests?

Due to reasons that I won't delve into here, I have opted to use jQuery ajax instead of Angular's http. This means I am making an ajax call to my php server. However, a problem arises where any code within the success/error blocks is confined to ...

Encountering a timeout error when connecting to MongoDB

Utilizing node.js v12.0.10, I have incorporated MongoDB database to establish a connection and update MongoDB collection with the following connection code: async.parallel({ RE5: function (cb) { MongoClient.connect(config.riskEngineDB ...

Transforming form command objects in Spring MVC using JavaScript or AJAX execution

I'm currently utilizing Spring MVC 3.0 for the development of a web application. Users have the option to retrieve customers by entering their ID, or simply submitting an empty form to display all customers that they can navigate through using button ...

Hide the Bootstrap slide menu with jQuery by clicking anywhere on the screen

Here is a Fiddle link: https://jsfiddle.net/r94dq2e4/ I have incorporated a slide-in menu from the left in my website using Twitter Bootstrap version 3. The menu appears when the navbar toggle button is clicked. This is the jQuery code responsible for ...