Rearrange the alignment of a series of neighboring divs in a creative manner

This question delves into the realm of conceptual thinking rather than just jQuery specifics. In my scenario, I am populating a container with divs that have a top value set in a non-linear manner. Each div's top value is calculated using a formula that considers the top position of the preceding div as well as the container's height (refer to line 33 of the fiddle).

// The formula below determines the top value for each new child added to the container
// The height is set at 100% of its parent, which is 20% of the body
// The newly added child will initially have a top value of 10%
(parseInt($(this).next().css('top'), 10) / $('#queue').height()) * 75 + (parseInt($('.newOne:last').css('top'), 10) * 2) + '%'

I stumbled upon this method somewhat serendipitously, and it seems to work adequately. However, if you envision any optimizations, please feel free to share :) I'm currently grappling with devising an elegant formula to smoothly adjust the children during a drag event. My theory involves tweaking the top value based on some manipulation of the left offset; yet, after hours of experimentation, I have not discovered a solution that maintains the original positions when dragging begins and continues adjusting the values seamlessly throughout. As I move left, the children should gradually approach a minimum top value of 10% (a child with a left offset of 0 will have a top value of 10%), and as I drag right, they should progressively return to their initial positions.

$('#queue').draggable({
    axis: "x",
    scroll: false,
    drag: function(){
        // Adjust the values of each child
        $('.newOne').each(function(){
            var percentLeft = $(this).offset().left / $('footer').width() * 100;
            var thisLeft = parseInt($(this).css('left'), 10) / $(window).width() * 100;
            var thisTop = parseInt($(this).css('top'), 10) / $('#queue').height() * 100;
            if (percentLeft >= 0){
                // Implement a gradual decrease in top value...
                // as the offset approaches 0 and reaches a minimum of 10%
                // Non-linear attempt but unsuccessful
                // $(this).css('top', $(this).css('top', 10 + (thisTop - 10 / thisLeft) + '%'));

                // Linear adjustment
                $(this).css({'top': 8 + (percentLeft/2) + '%'});
            }
        });
    }
});

http://jsfiddle.net/5RRCS/17/

P.S. I realize this is quite a challenging inquiry, but I hope someone is willing to take it on :)

Update: I came across the exponential method and tried something like this:

adjustTop = function(offset){
    return 100 * (1.0-Math.min(0.98,(0.83 + ( 0.17/ (Math.exp(0.007*offset))) )) ) + '%';
};
$(this).css('top', adjustTop($(this).offset().left) );

Answer №1

Here is a revised version that should meet your requirements.

To ensure consistency, I streamlined the top calculation by adjusting both the initialization and drag handlers to produce identical outcomes.

Instead of computing the child divs' positions based on their offset from the document, I restructured the methodology to utilize their relative position within the container.

I eliminated the need for z-index adjustments since the child divs are already appended to the parent with the correct stacking order - the farthest left child represents the final element in the container.

The height calculation for each child was contingent upon whether #queue's current position was left or right of its origin.

The iteration logic was also modified for uniformity in calculating the starting offset of the current elements:

$($('.newOne').get().reverse()).each(function (index) {
    $(this).css({
        'background': 'rgba(255,255,255,.80)',
        'top': calcTop($(this), index)
    });
});

For positioning the child elements, follow this code snippet:

function calcTop($ele, index) {
    // Calculations go here...
}

An issue was identified in the reset function where it failed to reset childCount back to zero:

$('#reset').click(function () {
    $('#queue').empty().css('left', 0);
    childCount = 0;
});

Check out the Demo Fiddle!

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

Long taps do not activate the context menu in the mobile interface, as noted in the Google Maps API

During the development of my project, I encountered an issue with the Google Maps API not functioning correctly on mobile devices. I am utilizing GMaps.js, but even that example does not properly support right-click (long tap event). Here is a snippet of ...

Inconsistency in Firebase data updates

Hey there, my code snippet below is responsible for capturing latitude and longitude values through a drag-and-drop marker. Although the latitude and longitude are continuously updated in the console when I log them, the same doesn't seem to happen wh ...

Having trouble resolving errors encountered while running the `npm run build` command, not sure of the steps to rectify

I am currently working on my first app and attempting to deploy it for the first time. However, I have encountered an error that I am unsure of how to resolve. When running "npm run build", I receive the following: PS C:\Users\julyj\Desktop& ...

Tips for saving data obtained from an ajax call

My jquery ajax function has a callback that creates an array from retrieved json data. Here's an example: success: function (response) { callback(response); }, The callback function, in this case createQuestionsArray(), populates ...

When dealing with multiple select fields, the second option will automatically be disabled once the user chooses an item from the list

Is it possible to create a select box where choosing one option will disable the other, and vice versa? Any tips on how this can be achieved? <select> </select> or <select> </select> ...

Implementing checkboxes for each API data in JavaScript

I am fairly new to this and I am currently working on a to-do list. I want to include a checkbox next to each item from the API to indicate whether it has been completed or not. <script type="text/javascript"> fetch('http://localhos ...

The Controller consistently receives a NULL value for the String variable passed from the View

I'm trying to send data from the View to the Controller using an Ajax call. However, the current code is passing NULL every time. Can someone please advise me on what I might be doing wrong? Here's the code in Index.cshtml: <input type="subm ...

Issue encountered when attempting to invoke a service from an Angular component within an office.js dialog

Our application utilizes Angular 5 and integrates Office.js to interact with Microsoft Office Word documents. Step 1: We use office displayDialogAsync to load the component. https://i.sstatic.net/uhT66.png Step 2: Inside the attribute-users component, an ...

"Discover the process of incorporating two HTML files into a single HTML document with the help of

I successfully created both a bar chart and a pie chart using d3.js individually. Now, I am trying to load these charts into another HTML file using jQuery. $(document).ready(function() { console.log("ready!"); $("#piediv").load("file:///usr/local ...

Sending a JSON object as a prop from one React.js component to another

I've been attempting to pass a JSON object retrieved by calling a REST API after submitting a form with user input. While I am successful in transferring the data to another component within the same file (this component is responsible for iterating o ...

Having difficulty retrieving the click event using a jQuery selector

I'm facing issues with my jQuery selector when trying to access a click event. Below is the HTML code snippet: <li class="handle-bars"> <span class="fa fa-bars pull-right text-primary m-t-10"></span> <span class="fa fa-co ...

Troubleshooting: CSS Pseudo :after doesn't apply to an anchor tag

I've created a pseudo CSS style for an anchor tag, which was working fine before. However, for some reason, it's no longer working. I tried using Chrome inspect element to add the CSS but it's not being read by the anchor tag. @font-face ...

Ensuring Consistent TD Heights in Email Designs

I am currently facing a challenge in building an HTML email, specifically in ensuring that two TD elements have the same height across all email clients. Since it is a responsive email design, I have opted to separate the columns into two tables instead o ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...

Having trouble attaching to ng-repeat

After creating a basic ASP.NET WEBApi that retrieves a list of customers, I am attempting to connect it with the UI. Here is my WEB Api Controller code: public class DummyController : ApiController { public HttpResponseMessage Get() ...

Starting point for Angular 2 app setup

What is the best way to handle data initialization in my app? For instance, if a user logs in and presses F5, I need to retrieve the current user data from the server before any other queries are executed, such as getting the user's orders. In Angular ...

Is there a way to compel Google Maps to load within my Angular application by implementing an Angular Directive?

I am encountering an issue where my Google Map fails to display most of the time. It seems that the map is not fully rendered when the rest of my data is populated in my Angular view. Is there a way to force the map to load? I have done some research and ...

The style attribute transforms the background-image url quotation to become &quot;

I'm currently working on creating a catalog component that will allow me to display images, titles, and descriptions multiple times. Below is the code for this component: import React from "react"; import '../pages/UI.css'; import ...

json array is only populated with the initial value

I am facing an issue with a local file that contains some JSON data. { "tournament": [{ "TeamName": "AS Roma", "TeamPlayer": "Rickard" } { "TeamName": "Inter", "TeamPlayer": "Bobban" }] }​ When I click the button, I attempt to pop ...

Cookie Request has not yet been removed

My webpage has a simple function where users can log in, and depending on whether the cookie exists or not, it will display either their name or a login button. However, I am encountering an issue with unsetting the cookie. I've tried troubleshooting ...