Attempting to devise a jQuery algorithm sorting method

To enhance the answer provided in this post: How to stack divs without spaces and maintain order on smaller screens using Bootstrap

I've been exploring ways to develop a jQuery script that dynamically adjusts the margin-top of div elements based on their accumulated height compared to adjacent columns.

The CSS:

div {outline:solid 1px red; }
// Setting small media container widths for code testing.
@media (min-width: 400px) {
.container {
    max-width: 1170px;
}
   .left {
    max-width:50%;
    width: 50%;
    float:left;
    clear:left;
} 
   .right {
    max-width:50%;
    width: 50%;
    float:left;
}  
}

@media (min-width: 150px) {
.container {
    max-width: 400px;
}
.col-sm-12 {
    width: 100%;
}
}   

The HTML:

<div id="1" class="left col-sm-12" style="height:100px;background-color:yellow;">DIV 1</div>
<div id="2" class="right col-sm-12" style="height:80px;">DIV 2</div>
<div id="3" class="left col-sm-12" style="height:50px;background-color:yellow;">DIV 3</div>
<div id="4" class="right col-sm-12" style="height:70px;">DIV 4</div>
<div id="5" class="left col-sm-12" style="height:20px;background-color:yellow;">DIV 5</div>
<div id="6" class="right col-sm-12" style="height:80px;">DIV 6</div>
<div id="7" class="left col-sm-12" style="height:50px;background-color:yellow;">DIV 7</div>
<div id="8" class="right col-sm-12" style="height:90px;">DIV 8</div>

The JavaScript:

$(function () {
// Extract div by id.
var idR = $("div").attr('id');
var idNumber = parseInt(idR);
// Checking if it's a right-aligned div element.
if((idNumber % 2 == 0) && (idNumber > 2)){

var className = $("div").attr('class');
var leftHeight = 0;
var rightHeight = 0;

for(int i = 0; i < idNumber; i++){
// Calculating left side heights accumulation.
if(className.localeCompare("left") == 0){
   leftHeight += $("#"+idNumber.toString()).height;
}
 // Calculating right side heights accumulation.
 if(className.localeCompare("right") == 0){
    rightHeight += $("#"+idNumber.toString()).height;
}

   var diff = leftHeight - rightHeight;
   // Determining which side is shorter.
   if(leftHeight > rightHeight){
        $("#idR").css({
        "margin-top":"-"+ diff + "px",
    });
   }
    else{
        var idL = (idNumber + 1).toString();
       $("#idL").css({
        "margin-top":"-"+ diff + "px",
        "clear":"both",
    });
    }
}
}
});

The Fiddle: http://jsfiddle.net/kermit77/hswxc06w/26/

https://i.sstatic.net/56ykK.png

The concept behind this approach is to apply the difference in height as a negative top margin to the shorter div, aligning it with the one above.

https://i.sstatic.net/y2aw1.png

Although I'm encountering issues and suspect multiple errors, I haven't been able to get it to function correctly through trial and error.

Any feedback or guidance would be greatly appreciated.


With assistance from the accepted solution, I managed to resolve this challenge. Full code available here:

Answer №1

Check out my unique approach to solving this issue.

I created a pair of additional divs and positioned the original divs behind them, then attached the new divs to the left and right based on their respective classes.

JS fiddle example
Here is the code snippet I used to place the existing divs inside the two new divs

$('#div1').css("float", "left");
$('#div2').css("float", "right");

$('#div1').append($('.left'));
$('#div2').append($('.right'));

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

Utilize jQuery to deactivate all click interactions except for the scrollbar

I am currently working on creating a page that is completely unclickable, both with right and left clicks, and I want to display a message when someone attempts to click. This may lead to some questions such as "Why would anyone want to do this? This s ...

Button click triggering XMLHttpRequest not functioning properly due to null

I am facing an issue with my webpage. When I click on a certain section labeled as "trigger," it is supposed to print the content in the "#content" page. However, I want it to redirect back to the "home" section when I click on the "BACK" button that appea ...

How can I simulate mouse position in a UIWebView?

Can the mouse position (x,y) for HTML-5 elements on a UIWebView be programmatically set using stringByExecutingJavascript in order to trigger hover, mouse over, and other interactions? ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

The hyperlink menu within the Bootstrap 4 navbar extends into the inline-form

Bootstrap 4's site suggests that a navbar with forms should function properly: I have used the class="form-inline" and at the same level in the HTML, the ul-tag with 3 hyperlinks. Check out this codepen example: http://codepen.io/anon/pen/eWOKXL?ed ...

What is the best way to add a style to every child element of a specific type using SCSS?

Is there a way in SCSS to target all child elements of a specific type with a certain style? For instance, if I want to add a class called 'radioCircles' to a div that will give all radio buttons inside that div a border-radius of 10px. Keep in m ...

In AngularJS, the execution of a subsequent AJAX call is reliant on the response of a preceding AJAX

Initially, I invoked the userSignupSubmit function. Within this method, another method called mobilenocheckingmethod is called. This method depends on the response from an AJAX call to make another AJAX call, but unfortunately, the second call does not w ...

Uh oh! There seems to be an issue with the ClerkJS frontendAPI option. Visit the homepage at https://dashboard.clerk.dev to retrieve your unique Frontend API value

Despite inputting the correct Clerk API keys, I'm encountering issues with the functionality of the ClerkJS API. I anticipate that the application should enable me to utilize the ClerkJS API for user authentication without any problems. ...

Ways to ensure the axios call is completed before proceeding with the codeexecution

I need to use axios to send a request and retrieve some data that I want to pass as a prop to a React Component. Here's my render function: render() { boards = this.fetchBoardList(); return ( <div className="app-wrapper"> ...

Tips for altering the selected color of a checkbox?

I'm trying to change the color of my checked checkbox to green and also adjust the size, but for some reason, only the size is changing in my code. I even attempted using `:checked:after` without success. input[type='checkbox']{ width: 1 ...

Creating an app using Ionic 1 that features scrollable tabs with the ability to handle overflow

My current code snippet is displayed below. On smaller mobile screens, all 7 tabs are not visible at once and instead appear in two rows which looks messy. I want to modify the display so that only 3 tabs are visible at a time and can be scrolled through. ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

Could anyone help me locate the section in the MUI documentation that explains the correct syntax for the commented code lines I am working on?

Before proceeding, please note that the ThemeProvider with theme={theme} has already been provided. Now, I will share two distinct sets of code files. These files contain sections commented out because they are not functioning as intended when implementing ...

Ways to extract specific HTML from a jQuery element

When fetching html from a website, how can I extract specific html content instead of getting all of it? I have attempted the following method: Before appending data to the target below container.html(data); I would like to perform something like data.f ...

Creating Pop-up Dialog Boxes in WebForms Using jQuery

I have implemented a Plugin in Webforms using jQuery UI dialog. Since I have a Content Place holder on my Form, I had to modify the code as shown below: <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> <link rel="stylesheet" ...

Is there a way I can incorporate v-for with a computed variable?

I am trying to display navigation items based on my authority and other conditions. Below is the code I am using: <template v-for="(subItem, index2) in item.children"> <v-list-item sub-group link :to="subItem.link" exact ...

Leveraging JQuery for activating an event with Bootstrap Scrollspy

I'm facing a challenge in capturing the Scrollspy event to execute a specific function. The Scrollspy feature is functioning correctly in terms of updating the active link on the navbar. However, I am struggling to capture the event for use in other p ...

struggling to update an array with user inputs on my to-do list app

I'm currently in the process of creating a small to-do list with some specific functionality. I want each text input (or a copy of it) to be added to an empty string, ensuring that the original input remains unchanged. The goal is to have a function t ...

The browser is only showing particular changes made to the CSS file

I'm currently working on a web project and have the following CSS and HTML code: style.css: body { background-color: red; font-size: 14px; font-family: Roboto,arial,sans-serif color: gray; } img { height: 92px; width: 272px; ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...