Creating impenetrable div elements with JavaScript or jQuery

I'm currently working on creating solid blocks using DIVs positioned side by side both horizontally and vertically. I've successfully achieved this when the divs have equal heights. However, an issue arises when a div has larger dimensions; it ends up being positioned below other divs instead of adjacent to them. You can see an example of this problem here: () Below is the code I am using:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
<style>
    body{margin:0px;padding:0px;font-family:Verdana, Geneva, sans-serif;font-size:12px;}
    #container{position:relative;}
    #container .box{width:143px;height:143px;background:#eee;padding:5px;position:absolute;}
    #container .s21{width:303px;}
    #container .s32{width:463px;height:303px;background:#F60;}
</style>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>

<script type="text/javascript">
    function relocate(){
        var browserWidth = $(window).width();
        var defaultWidth = 160;
        var yPos = 7;
        var xPos = 7;
        $('.box').each(function(i, obj) {
            elementWidth = $(this).width();

            if(xPos + elementWidth > browserWidth){
                yPos = yPos + 160;
                xPos = 7;
            }
            $(this).css('top',yPos+'px');
            $(this).css('left',xPos+'px');

            xPos = xPos + 17 + $(this).width();
        });
    }

    $(document).ready(function(){
        relocate();
        $(window).resize(function() {
            relocate();
        });
    });
</script>

</head>

<body>

<div id="container">
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box s32" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>
<div class="box" id="">
    Test
</div>

</div>

</body>
</html>

Thank you in advance for any assistance provided.

Answer №1

If you're looking to organize your .boxes inside #container, a good approach is to set them to "inline-block" and float them either left or right according to your preference. It's important to establish the order of the blocks beforehand. Here's a simple CSS box alignment example:

#container {
    white-space: nowrap;
}
.box {
    white-space: auto;        
    display: inline-block;
    vertical-align: top;
    float:left;
}

Check out this example on JSFiddle

If you need to rearrange them easily, it's best to assign predefined widths and heights (such as XS, S, M, L, XL, XXL - sizes) to the boxes. You can then place them in a matrix like this:

[ 2x1,  0,  1x2, 1x3 ],
[ 1x1, 1x2,  0,   0  ],
[ 1x1,  0,  1x1,  0  ]

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

Is it possible to send an ajax request within another ajax request?

I'm facing an issue with a php file that is sending an ajax request to another file located on a different domain name. The receiving parser then processes the information and sends it via ajax to yet another php file where the final action is carried ...

Dealing with errors when Ajax response is not defined

Trying to display errors when Ajax is unsuccessful, but struggling to access the specific error details. example Here is the information from the network tab playground {"message":"The given data was invalid.","errors":{"title":["The title field is requ ...

How come I am able to send back several elements in react without the need to enclose them in a fragment

This piece of code is functioning properly in React, displaying all the names on the page. However, I am questioning why it is returning multiple elements as a React component. Shouldn't they be wrapped in a single fragment? function App() { const n ...

Tips for transferring the clicked value to the next page

Recently, I started working with Ionic and developed an application using it. Now, I am facing a challenge where I need to pass the value from the first page to the second page. To illustrate this more clearly, I have attached two photos. Here is the imag ...

How to use JavaScript and regex to control the state of a disabled submit button

I have a challenge where I need to activate or deactivate a submission button in a form called btn-vote using JavaScript. The button will only be activated if one of the 10 radio buttons is selected. Additionally, if the person-10 radio button is chosen, t ...

Issues with Jquery datatable causing column header to overlap the table header

I am facing an issue with my datatable as the table is not displaying correctly. Could someone advise me on how to troubleshoot and fix this problem? Below is the code snippet in question: $(tbName).dataTable({ "sScrollX": "100%", "sScro ...

Activate $digest when a variable is modified by a node.js function

I am currently working on developing an application using node-webkit and AngularJS. Everything was going smoothly until I tried to make Angular watch over a "legacy variable" using the method outlined in this answer, which led to an Error: [$rootScope:inp ...

enhanced labeling for checkboxes in Vuetify

Below is a snippet of my straightforward code: <v-checkbox v-model="rodo" label="I consent to Terms and Conditions (click for more info)" :rules="termsRules" required ></v-checkbox> I am looking to keep the label simple with an option ...

SQL query using Ajax

I'm currently working on an Ajax call using a query string, but I've hit a roadblock midway through. My goal is to update a SQL table with the JavaScript sortable function. After an item has been moved up or down, I want to pass it through Ajax a ...

The use of HTML5 required attribute is ineffective when submitting forms via AJAX

Seeking advice on implementing basic validation for a newsletter form that only requires an email address. The current page layout doesn't allow space for jQuery error messages, so I attempted to use the HTML 5 required attribute. However, the form st ...

Using the jQuery.grep() method to sort through data

I have been attempting to filter data that is stored in a .js file using the jQuery.grep() method, but unfortunately, the data is not loading as expected. Data var myData = { "type": "FeatureCollection", "crs": { "type": "name", "properties": {"name": ur ...

Using Jquery along with the Foreach function

Currently, I am working on a form that allows clients to edit their keywords/tags. Once the keywords are submitted, they are stored in the database and retrieved using foreach and explode. Instead of displaying the values like "one,two,three," they are s ...

`Issues encountered with resizing the menu``

Looking to create a unique restaurant horizontal list bar for my application. The goal is to have a horizontal menu that displays 3 options on the screen at a time, with the middle one being the largest and the two flanking it smaller in size. As I scroll ...

Occasionally, there are instances when node.js combined with express.js and hogan.js may result in a blank page being

Most of the time, every feature in this app functions properly. However, there are instances when a blank page is displayed instead of the homepage (or any other page). Interestingly, making a minor adjustment to the affected view, such as adding a space o ...

The time format you have specified is not supported

Attempting to use the most basic moment test, but encountering issues. The following steps were taken: npm install moment In app.js file, I included the following: var moment = require('moment'); var testDate = new Date(); console.log(moment( ...

How can we align images above one another in a responsive manner using Bootstrap 3?

Looking for assistance with aligning and overlapping images on top of another image in Bootstrap while maintaining responsiveness. I've attempted the following: HTML: <div class="container"> <div class="row"> <div class="col-lg-12"> ...

Generate an XML document on the server with the help of SimpleXML and jQuery Ajax technology

I am facing a challenge in achieving my goal, which involves creating an XML file using an Ajax call. The code snippet below demonstrates my attempt at this, although it may not function correctly: HTML <html> <head> <!-- Including JQuery ...

Passing in additional custom post data alongside serializing with jQuery

function MakeHttpRequest( args ) { var dataToSend = "?" + $("form[name=" + args.formName + "]").serialize(); $.ajax({ type: "POST", url: args.url + dataToSend, data: { request: args.request }, su ...

Display PHP Array data in a table on a webpage

I need help arranging the results from a MYSQL database into an HTML table. Right now, each item is displayed in one column per row. Here is my current code: <?php $catagory=$_GET["q"]; $con = mysql_connect("localhost","cl49-XXX","XXX"); if (!$con) ...

List the acceptable favicon formats for Internet Explorer version 10 and above

When I say type, I'm referring to the file extension. My favicon displays correctly in Firefox, Chrome, and Safari, but someone suggested that the issue may be related to the favicon type. Is there a reliable online resource where I can find informa ...