Select the five previous siblings in reverse order using jQuery's slice method

I have a unique approach to displaying a series of divs where only 5 are shown at a time using the slice() method. To navigate through the items, I include an ellipsis (...) link after every 4th item, which allows users to easily move on to the next set of 5 items. If you're having trouble picturing it, here's how it would look with all the items displayed instead of just the 5:
< 1 2 3 4 … 5 6 7 8 … 9 10 11 12 … 13 14 15 16 >

The challenge arises when a user wants to go back and view the previous 5 divs. Clicking the back arrow should hide the current set and reveal the preceding 5 divs. While slice() doesn't allow for reverse functionality, selecting the previous 5 siblings presents another hurdle. Using prev() or nth-child won't quite solve this issue as desired. As someone who considers themselves beyond a beginner in jQuery but not quite a Jedi yet, I'm stuck on finding a solution without overcomplicating the function. Check out my work-in-progress fiddle here:
https://jsfiddle.net/nehLuj98/

$(".btn-nav").slice(0,5).show();
$(".btn-ellipsis").each(function(){
    var goNum = $(this).prev(".btn-num");
    var num = Number(goNum.attr("id"));
    var currentNum = $(this).find(".current");
    $(this).click(function(){
        $(this).hide();
        $(".btn-num").hide().slice(num,(num+4)).show().next(".btn-ellipsis").show();
        $(this).next(".current").removeClass("current");
        $(".btn-num").hide().slice(num,(num+4)).show().next(".btn-ellipsis").show();
        goNum.add("#"+(num+1)+"").addClass("current");
    });
    $(".btn-prev").click(function(){
        //Here's where I'd like to add the functionality to show the previous 5 items
        //$(".btn-nav").add(".btn-ellipsis").hide();
    });
});

Since I'm working with AngularJS, the dynamic generation of numbers from a .json file might play a role in this feature. The insertion of the ellipsis link every 4th numbered item accommodates variations in the number of links available. For simplification purposes, I've included it directly in the html for the fiddle.

TL;DR
Do you know of a way to achieve reverse functionality using jQuery's slice() method or select the previous 5 siblings differently?

Answer №1

If you review your existing code, one possible solution would be:

$(".btn-prev").click(function(){
    if ($('.current').attr('id') === '1' || $('.current').attr('id') === '4')
    return;
  var currentElip = $('.btn-ellipsis:visible');
    if (!currentElip.length)
    currentElip = $('.btn-next');
  else
    currentElip.hide();
  var goNum = currentElip.prevAll('.btn-ellipsis').prev(".btn-num");
  var num = Number(goNum.attr("id"));
  $(".btn-num").hide().slice(num-4,(num)).show().next(".btn-ellipsis").show();
    $(".current").removeClass("current");
    $("#"+(num)).addClass("current");
});

You can find detailed explanations and comments regarding the above code in this fiddle:

https://jsfiddle.net/nehLuj98/10/

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

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

Is there a way to transform this JSON string into a particular format?

When moving a string from view to controller, I have encountered an issue. Below is the ajax code I am using: var formData = $('#spec-wip-form, #platingspec-form').serializeArray(); var platingId = @Model.PlatingId; var form = JSON.s ...

Troubleshooting: Potential Reasons Why Registering Slash Commands with Options is Not Functioning Properly in Discord.js

While working on a Discord bot, I encountered an issue while trying to register a slash command with options for the ban command. The error message I received was: throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: ...

Discover the secret to effortlessly merging two properties into a harmonious entity called 'name' using ng-options!

Usually, our approach is ...}}_{{$index}}" ng-options="option.serial_no as option.NameRelation for option in fullFamilydetails" ng-model="obj.ch6a_decl_fam_memb_id"> On the Java side, I implement ... familyDetails.put("NameRelation", Emp_FamilyInfo ...

Presenting quiz questions using javascript

Currently, I am following the learning path on javascriptissexy.com and facing a challenge with displaying quiz questions in the best way possible. As a beginner student of JavaScript, my question is about how to approach developing the behavior of a quiz ...

Automated Copy and Paste Feature - JavaScript using Ajax

I am working on a unique auto-increment IMDB ID grabber that retrieves the ID as you type the name of a TV show. Currently, I have managed to create functionality where it checks if the field is empty; if not, it displays a button that directs you to a pag ...

combining all JavaScript script tags into a single tag

I'm currently working with wavesurfer.js and have the following setup: 'use strict' <!-- wavesurfer.js --> <script src="src/wavesurfer.js"></script> <script src="src/util.js"></script> <scrip ...

Add motion to the div element when hovering and moving the mouse away

Looking to add animation to a list moving from left to right and vice versa. Now, I want the list to animate from left to right when the mouse hovers over the div, and then animate from right to left when the mouse leaves the div. Can someone assist me wit ...

Prevent the query from being executed by halting the AJAX call

Within my web application, I have a specific button that triggers an AJAX call upon being clicked. On the server side, I need to run a query against a database. I am concerned about the execution time of these queries and worry that users may be impatient ...

HtmlUnitDriver fails to execute javascript while loading a page from a URL

My issue revolves around testing my website page, where elements displayed with javascript are missing when viewed through the HtmlUnitDriver. I am currently using selenium-java version 3.141.59 and htmlunit-driver version 2.33.3. Below is a snippet of my ...

What is the best way to prevent an element from reaching the border of the screen?

As a JavaScript beginner, I am working on creating a simple game. My objective is to prevent the player (20px x 20px) box from causing the screen to scroll. I want a fixed screen where the player cannot go beyond the edges of the screen. Below are my previ ...

The reason for the failure of the web API is due to the incorporation of the original controller's name by

I'm attempting to fetch data from a web-api controller within a razor page loaded by a standard controller. However, my $.getJSON() call fails because the getJSON method is appending the original controller name in front of the URL. How can I work ar ...

Inject the ng-repeat variable into a personalized directive

When working with an ng-repeat and a custom directive, I am facing the challenge of passing the "item" variable from ng-repeat to the directive. Here is an example code snippet illustrating this situation: <li ng-repeat="item in list"> <div c ...

Collaborating with multiple forms and files in PHP using jQuery and AJAX operations

Need help with the title for this question. There are two input fields and buttons in index.php <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"> <input type="text" class="for ...

Prevent jQuery from triggering the infinite scroll until the next page has been fully loaded

In my custom WordPress template, I utilize this code snippet to achieve infinite scroll functionality. The button that triggers the AJAX request is placed at the bottom of the page for user convenience. Here's how I use it to automatically trigger the ...

D3.js: Unveiling the Extraordinary Tales

I'm currently working on a project that requires me to develop a unique legend featuring two text values. While I have successfully created a legend and other components, I am facing difficulties in achieving the desired design. Specifically, the cur ...

Transfer data from a child component to a parent component in a React application

Currently, I am working on my second React app. This time, I am experimenting with nested components, unlike my previous project which only had a single component. The main focus of this project is a calculator app built using React. To guide my design pro ...

How can you retrieve the current server time within the MEAN stack (MongoDB, Express, Angular, Node)?

SCRIPT: exports.generate = function (req, res) { var note = new Note(req.body); note.author = req.author; console.log("1) PREVIOUS: "+note.author.prev.getTime()); console.log("Server Time is: "+getServerTime()); if (note.author.prev != null &a ...

Ensure child elements do not surpass parent size in HTML/CSS/Javascript without altering the children directly

I am intrigued by how iframes neatly encapsulate all site data within a frame and adjust it to fit the size. Is there any method to achieve this functionality in an HTML wrapper? Can the wrapper be configured so that regardless of the content, it is dis ...

Error encountered while using getElementsByTagName in Greasemonkey on a webpage built with extJS, showcasing a basic scenario

Currently, I am experimenting with Greasemonkey on a web-app that constructs the DOM step by step utilizing a substantial amount of Javascript and making use of the extJS library. When there is no Greasemonkey code in operation, the site loads as expected ...