Arrange the list in ul by swapping items while keeping the active item in its original position

I am new to scripting and looking for assistance with swapping li's in ul. Here are the scenarios: 1. When a user clicks on an anchor tag, the active item should move to the center position. 2. The list may not be in order and could be arranged in any way.

var swapElements = function(siblings, subjectIndex, objectIndex) {
  // Get jQuery of the subject
  var subject = $(siblings.get(subjectIndex));
  // Get the object element
  var object = siblings.get(objectIndex);
  // Insert the subject after the object
  subject.insertAfter(object);
}
$(function() {
  swapElements($('li'), 0, 1);
});
ul li {
  float: left;
  display: inline-block;
  list-style: none;
}

ul li a {
  color: #000;
  text-decoration: none;
  padding: 15px;
  display: block;
}

ul li.active a {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li><a class="nav-item" href="#"><span>Quality</span></a></li>
  <li><a class="nav-item" href="#"><span>Safety</span></a></li>
  <li class="active"><a class="nav-item" href="#"><span>People</span></a></li>
  <li><a class="nav-item" href="#"><span>Cost</span></a></li>
  <li><a class="nav-item" href="#"><span>Delivery</span></a></li>
</ul>

I have attempted to modify the code without success. Can someone please help me solve this issue? Thank you in advance.

Answer №1

Take a look at the code provided below, along with detailed comments for better understanding. Feel free to reach out if any part of it is unclear.

$(document).ready(function() {
function change() {

// 1. Remove the 'active' class from the currently active component
$('.active').removeClass('active');

// 2. Retrieve the HTML content inside the list element
var htm = $(this).html();

// 3. Remove the selected list element
$(this).remove();

// 4. Add a new list element after the 2nd or (n/2)th child
$('li:nth-child(2)').after('<li class="active">' + htm + '</li>');

// 5. Attach the change method to clicking on this new element
$('li:nth-child(3)').click(change);
}

// Call the change function when a list element is clicked
$('li').click(change);

});
    ul li {
      float: left;
      display: inline-block;
      list-style: none;
    }

    ul li a {
      color: #000;
      text-decoration: none;
      padding: 15px;
      display: block;
    }

    ul li.active a {
      color: red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <ul>
      <li><a class="nav-item" href="#"><span>Quality</span></a></li>
      <li><a class="nav-item" href="#"><span>Safety</span></a></li>
      <li class="active"><a class="nav-item" href="#"><span>People</span></a></li>
      <li><a class="nav-item" href="#"><span>Cost</span></a></li>
      <li><a class="nav-item" href="#"><span>Delivery</span></a></li>
</ul>

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

Tips for efficiently loading large datasets into a ListBox in an ASP.NET MVC application

I am currently developing a web application using ASP.NET MVC. The application requires users to select an item from a ListBox which could potentially have over 30,000 entries. Is there a way to dynamically populate the ListBox with contents using an Aja ...

Developing a React project that is steadily progressing

My React apps are taking an unusually long time to build when I use the "npm run build" command in the terminal. It's been over 15 minutes each time. Can anyone provide any insight into what might be causing this delay? ...

Eliminating an ngRepeat item from the $rootScope array does not automatically result in the item being removed from the html code

Attempting to eliminate an li from a ul using angular. Although the element is successfully removed from the array, AngularJS does not remove the li until it is interacted with, such as being hovered over or clicked. See the code below: app.js myApp.run( ...

Is there a way to refresh a different webpage within the current session?

In the world of Asp.Net 4, there is a form waiting to be filled with numeric data by the customer. However, this task can sometimes prove tricky as customers may struggle to calculate and input the total figure for each of the four fields. An innovative s ...

Executing a function after the AngularUI Bootstrap modal has been closed and the animation has completed

I'm encountering an issue with the Angular UI bootstrap modal that I need help with. My goal is to trigger a function once the dismiss animation of the Bootstrap modal is complete. However, the current code snippet triggers the cancel() function as s ...

creation of objects using constructors in Node.js

As I delve into the world of Node.js, a burning question has arisen - how can I make a function accept multiple strings in the form of an array? Picture this scenario: export default (config: Config) => { return { target: 'https://google.com ...

AngularJS display element within viewport

My div is extremely wide and contains many elements. I need a way to bring specific elements into view when a button is clicked. Is there an alternative to $anchorscroll that can achieve this? Looking for a solution for horizontally scrolling to a particu ...

Is there a method in ASP MVC to generate an object dynamically within the view that corresponds to the model and can be mapped to input fields for sending via Ajax?

Details of the Model: public class MyDerived: Base { public string FirstName { get; set; } public string LastName { get; set; } } Description of Controller's Action Method: [HttpPost] public ActionResult Add(MyDerived obj) { if (ModelSt ...

Adjust form elements dynamically depending on the selected option in a dropdown menu using Ruby on Rails

I currently have the following database tables set up: Departments ID| Department_name | Manager_ID Employees ID| Name | Department_ID Salaries ID| Employee_ID | Salary_Amount The departments table holds information about different departments within t ...

An easy way to incorporate a fade-in effect for every word in a text

I am trying to make the text "Eat. Sleep. Repeat." slide up and fade in one word at a time. I have experimented with various methods like anime.js, keyframes, and adding css classes, but so far none of them have worked for me. Here is the code I currently ...

Modifying the background color and linking it to a different class in Android Studio: A step-by-step guide

Recently, I developed a settings feature for my project that allows users to change the background color. However, I noticed that when I return to the home page, the settings are not saving or syncing properly. Any suggestions on how I can sync this info ...

EJS is refusing to render the HTML page

When utilizing Express with EJS to display the response from a database query as a basic Html page, an error is encountered in the development tools. "Access to fetch at 'https://o189131.ingest.sentry.io/api/5478725/envelope/?sentry_key=504fcb6 ...

Are module.exports and export interchangeable?

Imagine you're creating an npm library and you need to export your functions. Here's one way to do it: function a(){ } If you want to export them locally, you could do it like this: export function a(){ } Alternatively, you could achieve the ...

Is it possible to ensure that the bottom div in a column matches the width of the top div when both have dynamic widths?

Looking at the code snippet below: <div id="container"> <div id="top"> <img /> </div> <div id="bottom"> Some text, there we go. </div> </div> The <img> tag has a fixed height ...

Attempting to place a different span beneath the current span

Is it possible to add another span below the first span and keep it on the same line as the circle? Check out this link for reference The following is the HTML code snippet: <div class="dialog-box"> <div class="dialog-box-circle"></d ...

Using JavaScript to trigger a PHP script execution

I'm facing an issue with a server-side PHP script that connects to a database and retrieves data. It seems to work fine in a separate browser, but I can't seem to make it run properly from a script within HTML. Here's the code snippet causi ...

Preventing commits when encountering build or lint errors

Every git repository contains git hooks within the .git/hooks directory. I have included a npm run lint command in the pre-commit git hook. However, I am unable to prevent the commit if npm run lint returns an error. ...

Adjusting Graph Ranges: A Guide to Manually Setting X and Y-axis Limits in Jpgraph

Hey everyone, I'm looking to make some adjustments to my Jp graph... 1) First off, I need to adjust the X-axis range from '0' to '100' with a step size of '10'. 2) Next, I want to set the Y-axis range from '-5&apos ...

The DropDownList does not automatically refill with the previous selection after a page refresh

I'm encountering an issue with my HTML website where the second DropDownList is not being populated when I refresh the page or go back from a redirected page. How can I fix this? You can check out the problem I'm facing at GiveToTheYToday.org if ...

I'm facing an issue with converting my object to an array as I keep getting the message: "ERROR TypeError: undefined

ERROR TypeError: undefined is not a function Why am I unable to convert my object to an array? This error keeps popping up as I attempt to map all the items that are currently objects but need to be converted into arrays for mapping. How can I accomplish ...