Is it possible to assign a numerical value to the prev() function or the prevUntil() function in jQuery?

Is there a way to apply a specific style to the six previous and six next items of a list, while giving a different style to those outside of this range using only CSS? I am currently using a functional but redundant jQuery code for this purpose. Can the prev() or prevUntil() functions be specified with a numeric value, like prev(6) or next(6)? Or should I consider using slice() instead?

Below is the jQuery code snippet I am using (where $navigationLink/s refer to anchor links on the page).

     if (!$navigationLink.parent().hasClass('sub-menu-current')) {
          $navigationLinks.parent().removeClass('sub-menu-current');
          $navigationLink.parent().addClass('sub-menu-current');
          $('li').removeClass('sub-menu-previous-1');
          $navigationLink.parent().prev().addClass('sub-menu-previous-1');
          // code for other previous and next items left out for brevity...
          $('li').removeClass('sub-menu-previous-6');
          $navigationLink.parent().prev().prev().prev().prev().prev().prev().addClass('sub-menu-previous-6');
          $('li').removeClass('sub-menu-next-6');
          $navigationLink.parent().next().next().next().next().next().next().addClass('sub-menu-next-6');                  
        } 

Note: Ideally, the number of previous and next items to be styled should match the viewport, but this might be a more complex task to achieve compared to the current implementation.

Answer №1

To make the code more concise, you can utilize the combination of the prevAll/nextAll function along with slice. Essentially, this allows you to target all preceding elements and then select only the first six.

Once you have grouped the elements, you can employ the addClass method with a callback to assign a class based on the index.

Below is a sample demonstration:

let $test_span = $( 'span' ).eq( 16 ).addClass( 'current' );

$test_span.parent().prevAll().slice( 0, 6 ).addClass( i => `previous-class-${i + 1}` );

$test_span.parent().nextAll().slice( 0, 6 ).addClass( i => `next-class-${i + 1}` );
.current{ color:green; }
[class^="previous"]{ color : red }
[class^="next"]{ color : blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>1</span></div>
<div><span>2</span></div>
<div><span>3</span></div>
<div><span>4</span></div>
<div><span>5</span></div>
<div><span>6</span></div>
<div><span>7</span></div>
<div><span>8</span></div>
<div><span>9</span></div>
<div><span>10</span></div>
<div><span>11</span></div>
<div><span>12</span></div>
<div><span>13</span></div>
<div><span>14</span></div>
<div><span>15</span></div>
<div><span>16</span></div>
<div><span>17</span></div>
<div><span>18</span></div>
<div><span>19</span></div>
<div><span>20</span></div>
<div><span>21</span></div>
<div><span>22</span></div>
<div><span>23</span></div>
<div><span>24</span></div>
<div><span>25</span></div>
<div><span>26</span></div>
<div><span>27</span></div>
<div><span>28</span></div>
<div><span>29</span></div>
<div><span>30</span></div>
<div><span>31</span></div>
<div><span>32</span></div>
<div><span>33</span></div>
<div><span>34</span></div>
<div><span>35</span></div>
<div><span>36</span></div>
<div><span>37</span></div>
<div><span>38</span></div>
<div><span>39</span></div>
<div><span>40</span></div>

Answer №2

Utilize jQuery's index function to determine the position of the current element among its siblings. This information can then be used to select other elements using jQuery's eq function. Here is an example:

for(var i = -10; i < 11; i++)
    if(i !== 0)
        $('div').eq($('#current').index() + i).css('background-color', 'blue');

Some refactoring may be necessary, but this should get you started in the right direction.

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

What is the best way to customize image transparency using javascript?

Looking to create a webpage that shows an image for a specified duration before smoothly transitioning to another image that includes a clickable link. Wondering how to accomplish this using javascript? I am aware that it can be done with Flash, but it mu ...

Expanding image in card to fit device width using Ionic

Currently utilizing the ionic framework and attempting to expand the image within the card to fit the device width. Referencing the example provided here, here is my current code progress. <div class="list card"> <div class="item item-avatar" ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

Issue with Bootstrap 4 navbar functionality on smaller screens

I'm currently in the process of integrating a navbar that transforms the navbar choices into a dropdown menu on smaller screens (as illustrated in the documentation available here). However, I am encountering an issue where the button responsible for ...

Is it possible to verify the user's authentication by confirming the presence of a JWT in their localStorage?

I am currently working on a project that requires JWT authentication. I have set up a registration form and login page where users receive an authorityToken and it is saved in localStorage. Once the user logs into their account : ` $("#btnLogin").click( ...

How do I switch between liking and unliking a post using Ajax's success response?

I have successfully implemented code to insert or delete likes from the database, and it functions correctly upon page refresh. However, I am struggling to figure out how to make it toggle upon clicking. I have attempted various online solutions without su ...

JavaScript - Modify the proposed content prior to inserting it into the input field

In my current project, I have implemented a feature using jQuery UI - v1.11.4, where an HTML textbox utilizes a JavaScript autocomplete functionality. The suggested string for the textbox is created by concatenating several columns (patient_no, patient_nam ...

The issue with $.parseJSON when encountering double quotes

Could someone please clarify why a JSON string with double quotes can disrupt the functionality of $.parseJSON? This example works: [{"type":"message","content":{"user":"tomasa", "time":"1321722536", "text":"asdasdasd"}}] And so does this one: [{"type" ...

Jquery for controlling the navigation menu

I'm new to JavaScript and facing 3 challenges: 1. When I click on the parent <li>, the correct content of the child <sub> does not show up. Each category like "colors, shapes, sizes" should have corresponding child categories like "green, ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

What is the best way to create a CSS grid with horizontal overflow?

I'm currently working on a 4-column layout using CSS grid. As the browser width reaches a specific breakpoint, I want the first column to be fixed on the left side of the browser (X-axis) while the other columns scroll under it. Right now, I am utiliz ...

Jquery's remove function fails to function correctly when used on a cloned element

I am facing an issue where I have a list of rows that need to be deleted. However, when I attempted to use jQuery's remove function, it only removed the original row and not its clone. My goal is for the parent element of the parent to be removed when ...

Customizing font sizes for individual fonts within the same font family

I am designing a website in a language other than English. This means that the text on the webpage will be a mixture of English and other languages. In order to make sure the text displays correctly, I have set the font-family like this: p{ font-family: ...

The functionality of JQuery's ajax post request is not functioning properly as intended

Link to the page: localhost/mysite/create-user This is the block of code: <form class="form-horizontal" name = "signUp1F" id = "signUp1F"> <input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = ...

Adjust the <h1> tag's size using responsive Bootstrap design

Is it possible to adjust the font size of the <h1> tag specifically for small and extra small screens? The default size of the <h1> tag is suitable for medium screens but appears very large on small and extra small screens. I would like to cu ...

Attempting to modify background by manipulating the state in Reactjs

I'm currently working on an app that features various games. My goal is to allow users to click a button and have the game display on the screen, with the background color changing as well. I aim to utilize state to control the overall background of t ...

Pace.js doesn't bother waiting for iframes to completely load before moving on

On my website, I am using pace.js but encountering issues with pages containing iframes. Is there a method to ensure that pace.js considers the content loading within those iframes? I attempted to configure paceOptions to wait for the iframe selector to l ...

Having trouble with your GitHub Pages site displaying properly on desktop but working fine on mobile?

I am facing an issue with my GitHub pages site on a custom domain. It works perfectly fine on mobile, but when I try to access the same URL from desktop, I encounter a DNS_PROBE_FINISHED_NXDOMAIN error. Any suggestions on why this might be happening? You c ...

Guide to using Ajax to load a partial in Ruby on Rails

Whenever a search is triggered, I have a partial that needs to be loaded. This partial can take a significant amount of time to load, so I would prefer it to be loaded via Ajax after the page has fully loaded to avoid potential timeouts. Currently, my app ...