jQuery: changing the order of list elements with the eq method

I've been tackling a challenge with designing a navigation bar that consists of 3 items. The goal is to have the clicked item move to the center position on the horizontal navbar while re-arranging the order. Here's the code snippet I've come up with so far:

$('li').mousedown(function(e){
    $('li').addClass('flanking');
    $(this).removeClass('flanking');

    $('ul li:eq(0)').after($(this));

    if( $(this) == '(ul li:eq(0)' ){
        $('ul li:eq(2)').prependTo('ul');
    };
});

Although this code successfully handles rearranging the second and last list items when clicked, it fails to do so for the first item. In an attempt to address this issue, I tweaked the if statement as follows:

if( $(this) == $('ul li:eq(0)') ){
    $('ul li:eq(2)').prependTo('ul');
};

Unfortunately, this adjustment didn't yield the desired result either. Could someone offer insights on how to identify if the clicked 'li' corresponds to the first in the 'ul', thus enabling its relocation to the middle? Your assistance is greatly appreciated.

Update: Check out Jaak Kütt's answer for a scalable solution along with a functional demo, Gokhan Arik's use of eq method and correct syntax for the if statement, and Birrel's impressive animation effects.

Answer №1

Edit: I have developed a more versatile solution that does not depend on the number of elements in the list. This solution positions the clicked element in the center (or closest to the center if there is an even number of elements), while moving the other elements between the starting and ending points towards the top or bottom, depending on their original position.

You can view this jsFiddle example which includes 4 lists with different lengths (in <li> and <p> examples) and fewer line breaks.

$('li').mousedown(function (e) {
    var self = $(this),
        length = self.siblings().length + 1,
        middle = length / 2 - 1,
        list = self.parent().children(),
        i = self.index() - 1;
    if (length % 2) {
        $()[i < middle ? 'after' : 'before'].call(
            list.eq(Math.round(middle)), 
            self
        );
    } else {
        list.eq(
            Math[i < middle ? 'ceil' : 'floor'].call(null, middle)
        ).after(self);
    }
});

PS1: The "flanking" class mentioned by the OP has been removed from the example as it was not crucial for the functionality.

PS2: Any suggestions on improving the algebra used in this code will be highly appreciated! :D

Answer №2

Update your current if condition with the following:

if( $(this)[0] == $('ul li:eq(0)')[0] ){
        $('ul li:eq(2)').prependTo('ul');
};

It's important to keep in mind that a jQuery selector returns an array of objects, not just a single item.

Answer №3

Check out this link for a demonstration with animation, currently functioning smoothly in Chrome.

Markup:

<div class="container">
    <ul>
        <li class="left_side">A</li>
        <li class="center">B</li>
        <li class="right_side">C</li>
    </ul>
</div>

CSS Styling:

* {
    padding: 0px;
    margin: 0px;
}
.container {
    width: 310px;
    position: relative;
    margin: 10px;
}
ul li {
    display: block;
    width: 100px;
    height: 25 px;
    background: #099;
    cursor: pointer;
    float: left;
}
.left_side {
    position: absolute;
    top: 0px;
    left: 0px;
}
.right_side {
    position: absolute;
    top: 0px;
    left: 210px;
}
.center {
    position: absolute;
    top: 0px;
    left: 105px;

}

JavaScript Functionality:

$('li').click(function () {
    // If not center item and not currently animating...
    if (!$(this).hasClass('center') && !$('.center').is(':animated')) { 

        if($(this).hasClass("left_side") ){ 
            $( this ).switchClass( "left_side", "center", 1000);
            $( '.center' ).switchClass( "center", "left_side", 1000);
        }else{ 
            $( this ).switchClass( "right_side", "center", 1000);
            $( '.center' ).switchClass( "center", "right_side", 1000);
        }
    }
});

NOTE: Make sure to include TWO external resources needed for this demo. You can access and download them here and here.

Answer №4

I recently completed a project where I added animation to re-arrange list items based on user interaction. The task was to work with a list of five elements:

1   2   3   4   5   

The goal was to rearrange the order when the user clicked on the first element, resulting in the following layout:

5   4   1   2  3

You can view the functionality in action on my Jsfiddle.

$('.horizontal li').on('click', function (e) {
    $(this).addClass('active').siblings().removeClass('active');
    // rest of JavaScript code here...
})

// CSS styles for the elements

If you want to see the full code implementation and styling details, feel free to check out the JSFiddle link provided above.

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

Managing loading and changing events using Angular, jQuery, and Web API

I am populating a dropdown select using ng-repeat. <select onchange="ChangeMonth()" id="month"> <option ng-repeat="(key,val) in Months" ng-selected="val==ActiveMonth" value="{{key}}"> {{val}} ...

Development of Chrome Extensions, JavaScript dilemma

Hey there, I'm new to JavaScript and I've been diving into the world of creating Chrome extensions. I'm trying to set up a content script and browser action, but I'm struggling to get it up and running. I know I'm probably making a ...

Is it possible to scroll a div on mobile without the need for jQuery plugins?

Upon investigating the initial query, we managed to implement D3js for identifying a scroll event. This allowed us to scroll the div #scroll-content from any location on desktop devices. However, we encountered an issue where this method does not function ...

Spotting the Visible Element; Detecting the Element in

Currently, my webpage has a fixed header and I am facing the challenge of dynamically changing the styling of the li elements within the navigation based on the user's scrolling position. To achieve this, I believe the most effective approach would b ...

"Enhancing User Authentication with Firebase Email Verification in React Native

Does Firebase have a feature that allows me to verify if an email confirmation has already been sent to a user? I am able to check validation, but I need to determine whether the verification email has already been sent in order to decide if it needs to be ...

Creating a sidebar navigation in HTML and CSS to easily navigate to specific sections on a webpage

Here's a visual representation of my question I'm interested in creating a feature where scrolling will display dots indicating the current position on the page, allowing users to click on them to navigate to specific sections. How can I achieve ...

Tips for adding responses to input fields in AngularJS

I am looking to populate data into 3 inputs based on the JSON response I receive from my node server. However, despite receiving a response, I am unable to input it into the designated fields. Controller: $scope.edit = function(id, contact) { console.log ...

rating-widget not displaying when performing an ajax request

Having an issue with the star rating plugin () while using an ajax function for searching and filtering. The star rating displays correctly when the page initially loads https://i.stack.imgur.com/eaOmu.png However, when utilizing the filter and search fu ...

Tips for transitioning this JavaScript code into jQuery syntax

Below is my JavaScript code: javascript: function executeCode() { var d = document; try { if (!d.body) throw (0); window.location = 'http://www.example.com/code?u=' + encodeURIComponent(d.location.href); } catch (e) { ...

Adjust the initial scroll position to - apply overflow-x: scroll - on the specified element

I have an image that can be scrolled to the right on screens that do not fit the full width, but I want the center of the image to be displayed first instead of the left side. Below is my React code: import React, { useEffect, useRef, useState } from &qu ...

Utilizing Ionic for local data retention

Seeking assistance with connecting my app to local storage in order to save data on the user's device without resetting every time the app is closed. Struggling to link local storage to an array of objects. Any guidance would be highly appreciated. Re ...

Unable to locate item by its identification number

Search for results in the index and return them. Method: async fetchIndex(req,res){ const userResults = await Usuario.find(); res.json(userResults); }, Route: routes.get('/api/usuarios', Usuario.fetchIndex); Having trouble ...

Implementing a search filter for special characters in AngularJS

Looking to filter an array of players by their names, but facing a challenge with special characters in the names. Found a code snippet on Google that looks like this: $scope.modelFilterNormalized = function(){ if($scope.modelFilter) return $sco ...

Using socket.io-client in Angular 4: A Step-by-Step Guide

I am attempting to establish a connection between my server side, which is PHP Laravel with Echo WebSocket, and Angular 4. I have attempted to use both ng2-socket-io via npm and laravel-echo via npm, but unfortunately neither were successful. If anyone h ...

Encountering a display issue within a port using Express

Recently, I enrolled in an advanced ExpressJS course. While exploring the course website, I stumbled upon the "hello world" section. Intrigued, I decided to copy and paste the code provided below: const express = require('express') const app = ex ...

Retrieving a single object from an array in node.js utilizing elemMatch

My goal is to extract a single object from an array of objects in a data collection using elemMatch. Here is the sample data: [ { "_id": "5ba10e24e1e9f4062801ddeb", "user": { "_id": "5b9b9097650c3414ac96bacc", "firstName": "blah", ...

What's causing this error with jQuery and JSON?

When utilizing the following code snippet: - $.getJSON("admin.php?format=json", { module: "data", action: "allBusinessUnitsByClientName", clientname : $('#client').val() }, function(json) { $.each(json.items, function(i,item){ alert ...

What are the best ways to stop jQuery events from propagating to ancestor elements?

I have a collection of nested UL's that follow this structure: <ul class="categorySelect" id=""> <li class="selected">Root<span class='catID'>1</span> <ul class="" id=""> <li>First Cat<span ...

Different techniques for retrieving elements generated by ng-repeat from their containing parent

Let's keep it simple - imagine we have a directive called headSlides. This directive's template includes an image that is being repeated using ng-repeat: <img class="bg" ng-repeat="image in images" ng-src="{{image.src}}"> I need to access ...

Can JavaScript be used to bypass AJAX cookies?

Is there a way in JavaScript to programmatically ignore server-sent cookies without adjusting browser settings? We have implemented plugins on our web server that periodically update our security cookie, resulting in compatibility issues with certain URLs ...