Issues arise with the functionality of custom jQuery sliders

I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated.

My Objective:

I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is clicked, the current panel should hide and the previous panel should appear. The panels are indexed as 1, 2, and 3. If the current panel is the first one and "previous" is clicked, then the third panel should be displayed. The same logic should apply when clicking the "next" button. Below is the HTML and JS code I am currently using:

HTML:

<div class="panel-slider">
    <div class="panel" id="1">
        <div class="panel-header">News Update 1</div>
        <div class="panel-body">
            <img src="img/news-update.jpg" class="img-responsive" />Lorizzle pizzle ma nizzle dope amizzle, consectetuer crazy elit. Dope dope velizzle, fo shizzle my nizzle volutpizzle, shizzlin dizzle fo shizzle, gravida fo shizzle, arc</div>
    </div>
    <div class="panel hide" id="2">
        <div class="panel-header">News Update 2</div>
        <div class="panel-body">
            <img src="img/news-update.jpg" class="img-responsive" />Lorizzle pizzle ma nizzle dope amizzle, consectetuer crazy elit. Dope dope velizzle, fo shizzle my nizzle volutpizzle, shizzlin dizzle fo shizzle, gravida fo shizzle, arc</div>
    </div>
    <div class="panel hide" id="3">
        <div class="panel-header">News Update 3</div>
        <div class="panel-body">
            <img src="img/news-update.jpg" class="img-responsive" />Lorizzle pizzle ma nizzle dope amizzle, consectetuer crazy elit. Dope dope velizzle, fo shizzle my nizzle volutpizzle, shizzlin dizzle fo shizzle, gravida fo shizzle, arc</div>
    </div>
    <div class="panel-slider-controls"> <a href="#" class="pull-left">Prev</a>
 <a href="#" class="pull-right">Next</a>

    </div>
</div>

JS:

var panel_index = 1;

$(".panel-slider .panel-slider-controls a").click(function () {
    var that = $(this);
    $(".panel[id=" + panel_index + "]").addClass("hide");
    if (that.text() == "Prev") {
        panel_index--;
        if (panel_index > 1) {
            $(".panel[id='" + panel_index + "']").removeClass("hide");
        } else {
            $(".panel[id='3']").removeClass("hide");
        }
    } else { //it's Next
        panel_index++;
        if (panel_index < 3) {
            $(".panel[id='" + panel_index + "']").removeClass("hide");
        } else {
            $(".panel[id='1']").removeClass("hide");
        }
    }
});

The Issue at Hand:

The behavior of the slider is unexpected and abnormal. You can see the problem in action through this fiddle.

Could someone please explain why this is happening and help me resolve the issue?

Note: It would be greatly appreciated if someone could assist in removing the hard-coded IDs and making the slider work seamlessly regardless of the number of div elements present. Thank you! :)

Answer №1

Check out this jsBin demo

To implement this functionality, simply add a class (e.g. next-news) to your buttons. Make sure your JS logic does not rely on text, as even an extra space could cause it to break.

<a href="#" class="pull-left  prev-news">Prev</a>
<a href="#" class="pull-right next-news">Next</a>

With just the following code snippet, you can achieve the desired effect:

var $panel = $('.panel-slider .panel'),
    idx = 0;

$(".prev-news, .next-news").click(function () {
    $panel.addClass("hide");
    idx = ($(this).hasClass('next-news') ? ++idx : --idx) % $panel.length ;
    $panel.eq(idx).removeClass("hide");
});

Answer №2

I have successfully implemented the solution without using any IDs as per your request. The code now dynamically handles any number of .panel elements. You can check out the working example at this link.

HTML Structure:

<div class="panel-slider">
    <div class="panel">
        <div class="panel-header">News Update 1</div>
        <div class="panel-body">
            <img src="img/news-update.jpg" class="img-responsive" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget turpis vitae ante imperdiet congue.</div>
    </div>
    <div class="panel">
        <div class="panel-header">News Update 2</div>
        <div class="panel-body">
            <img src="img/news-update.jpg" class="img-responsive" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget turpis vitae ante imperdiet congue.</div>
    </div>
    <div class="panel">
        <div class="panel-header">News Update 3</div>
        <div class="panel-body">
            <img src="img/news-update.jpg" class="img-responsive" />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam eget turpis vitae ante imperdiet congue.</div>
    </div>
    <div class="panel-slider-controls"> <a href="#" class="pull-left">Prev</a>
 <a href="#" class="pull-right">Next</a>

    </div>
</div>

CSS Styling:

.panel:nth-child(n+2) {
    display: none;
}

jQuery Script:

$(".panel-slider-controls a").click(function () {

    var self = $(this);

    if(self.hasClass('pull-left')) {

        var prevPanel = $('.panel:visible').prevAll('.panel').first();

        if(prevPanel.size() == 0) {

            prevPanel = $('.panel').last();

        }

        $('.panel').not(prevPanel).hide();

        prevPanel.show();

    }
    else if(self.hasClass('pull-right')) {

        var nextPanel = $('.panel:visible').nextAll('.panel').first();

        console.log(nextPanel.size());

        if(nextPanel.size() == 0) {

            nextPanel = $('.panel').first();

        }

        $('.panel').not(nextPanel).hide();

        nextPanel.show();

    }

});

Answer №3

If you're struggling to fix a problem, check out this helpful resource: http://jsfiddle.net/P6RfU/
It seems like the issue may have been caused by not properly adjusting the index when nearing the limits.

if (panel_index > 1)
{
    panel_index--;
    $(".panel[id='" + panel_index + "']").removeClass("hide");
} 
else 
{
    panel_index=3;
    $(".panel[id='3']").removeClass("hide");
}

I hope this explanation clarifies things for you. Feel free to ask if any part of the code is unclear!

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 - maximize the contrast between background and foreground colors in order to enhance

I'm dealing with a bar column that changes color based on the percentage value. However, some of the text is not visible to users because it falls within the white section of the bar. When selected, the text becomes visible but not otherwise. Is the ...

A guide on looping through an array enclosed within an object with the help of ng-repeat

I am trying to retrieve data from an API endpoint that returns a single object. Within this object, there is an array called video which I want to iterate over and display all the links stored in the array on the view. The JSON object returned by the API: ...

Issues with redirection to registration page in PHP Slim framework

When I access localhost/path/home, it takes me to the homepage where I can either login or signup. Clicking on either option should redirect me to localhost/path/login or localhost/path/signup respectively for the login or signup page. However, there seem ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

Adjust the classes of the static navigation bar based on the background of the section it is positioned over

In the process of developing a website using Bootstrap 4, I encountered a challenge with sections featuring both light and dark backgrounds along with a fixed navbar. The navbar, which is set to dark using the css class bg-dark, becomes indistinguishable ...

I need help getting my Vue.JS project to function properly when it is deployed on a server

After creating a new VueJS project using the Vue UI, I noticed that everything runs smoothly locally at http://localhost:8080/ with no errors. However, when I build the project and upload the files from the dist folder to my hosting package via FTP, I end ...

Before accessing the page, please ensure to make a double request

Encountered a weird issue, While inspecting the network tab in Chrome devtools, I noticed that my Vue app is making double requests to the same endpoint :/ Here's a snippet of my code: In the router section, I have a beforeEach function. When I navig ...

Encountering an issue with top-level await in Angular 17 when utilizing pdfjs-dist module

While using the Pdfjs library, I encountered an error message that reads: Top-level await is not available in the configured target environment ("chrome119.0", "edge119.0", "firefox115.0", "ios16.0", "safari16.0" + 7 overrides) /****/ webpack_exports = g ...

Issue: Difficulty in submitting a form using Ajax.BeginForm in ASPNET MVC

I am encountering an issue with a form in aspnet mvc that utilizes the Ajax.BeginForm helper. When I submit the form, I receive the following error in the console: Syntax error, unrecognized expression: label[for='[0].Selected'], label[for=&apos ...

What is the limit of CSS includes that IE can process?

While working on theming Drupal, I encountered an unusual issue. After enabling a few modules that added 5 to 10 link tags to the page, I noticed a strange behavior in different browsers. Firefox successfully added the new stylesheets to the cascade, but i ...

Utilizing React Native to Query, Filter, and Save a Single Document Field Value from Firestore Database into a Variable/Constant

My current task involves setting up a Firebase Firestore Database in order to filter it based on a specific field value within a document. The collection I am working with is named "PRD" and consists of thousands of documents, each sharing the same set of ...

The mixin 'media-breakpoint-only' is not defined

Recently, I decided to delve into coding with Bootstrap4 and Sass. I made sure all the necessary configurations were in place for my environment/project setup: including ruby 2.3.1p112 (2016-04-26 revision 54768) [i386-mingw32] and a list of installe ...

When quickly typing, the input formatting using a computed property in Vue.js is not getting applied

Is there a way to format data in the following manner: m:ss, while restricting the input textbox to display only 3 characters or fewer? (m = minute, s = seconds) The code snippet below successfully formats the data in m:ss format. However, when entering m ...

Submitting data from a dropdown menu using Ajax in Struts 2: A step-by-step guide

I have a select tag with the s:select element inside a form. My goal is to send a post request to the specified action using Struts 2 json plugin. I do not have much knowledge in javascript or jquery. <s:form action="selectFileType" method="post" ...

Display JSON data in a hierarchical tree structure using AngularJS

Looking to display three nodes of a JSON file as a tree using AngularJS. The nodes are data.key, data.parentItem, and data.title. Below is the JavaScript code: var phonecatApp = angular.module('myApp', []) phonecatApp.controller('myContr ...

Retrieve information from various MongoDB collections

Greetings! I currently have a database with the following collections: db={ "category": [ { "_id": 1, "item": "Cat A", }, { "_id": 2, "item": "Cat B" ...

please transmit the id (or retrieve the id from the router path)

I have a basic blog built with React/Redux for the frontend, featuring user registration and articles. I ran into an issue when trying to pass the article ID to the editor component. The form is the same, but the paths differ for adding new articles and ed ...

Utilizing Windows Azure and restify for node.js Development

I have an azure website with a URL like: . In my server.js file, I have the following code: var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify ...

Having difficulty linking the Jquery Deferred object with the Jquery 1.9.1 promise

I have been developing a framework that can add validation logic at runtime. This logic can include synchronous, asynchronous, Ajax calls, and timeouts. Below is the JavaScript code snippet: var Module = { Igniter: function (sender) { var getI ...

Show alerts that automatically disappear after a set amount of time

I have successfully implemented code that displays alerts for a specific period of time, indicated by (alert alert-warning). Additionally, I want to display another type of alert, (alert alert-success), for a certain amount of time, after which the page sh ...