Struggling to generate a 16x16 grid of divs with jQuery, encountering issues with divs constantly overlapping each other

Currently working on a small project for an online course where I need to create a 16x16 grid of divs using jQuery for DOM manipulation. However, I've encountered an issue - the divs are overlapping each other. As a beginner seeking constructive criticism, any feedback would be greatly appreciated. Thank you!

<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="EASP.css">
<head>

    <title></title>
</head>
<body>
    <div id="container"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="EASP.js"></script>
</body>
</html>

#container {
    background-color: red;
    height: 192px;
    width: 192px;
}
.unit {
    background-color: blue;
    height: 10px;
    width: 10px;
    margin: 1px;
    display: inline-block;
}


$(document).ready(function() {
    var unit = $("<div class='unit'></div>");
    for(var x = 0; x < 2 x++) {
        for(var y = 0; y < 2; y++) {
            unit.appendTo('container');
        }
    }
});

Answer №1

Here are a few issues to address:

  1. The CSS selector needs to be updated to #container since you are referencing it by ID.
  2. Ensure that there is a semicolon at the end of your first loop statement.
  3. Within the second loop, make sure to define div.unit as you intend to add a new DIV element in each iteration:

After making these corrections, the code should function properly:

$(document).ready(function() {
    for(var x = 0; x < 16; x++) {
        for(var y = 0; y < 16; y++) {
            var unit = $("<div class='unit'></div>");
            unit.appendTo('#container');
        }
    }
});

View the JSFiddle demonstration

Answer №2

Check out the live demo here. Here is the code snippet:

HTML

<div id="wrapper"></div>

CSS

#wrapper {
    background-color: green;
    height: 150px;
    width: 150px;
}

.box {
    background-color: yellow;
    height: 15px;
    width: 15px;
    margin: 2px;
    display: inline-block;
}

JavaScript

$(function() {
    for (var i = 0; i < 25; i++) {
        $("<div>").addClass("box").appendTo("#wrapper");
    }
});

Answer №3

The elements are not overlapping due to a mistake in your code. You inadvertently created only one div and appended it to the container twice in the loop, resulting in only one visible div. To rectify this issue, make sure you create and append a new div within the for loop.

Additionally, there are some syntax errors in your original code that need to be fixed:

$(document).ready(function() {

    for(var x = 0; x < 2; x++) {
        for(var y = 0; y < 2; y++) {
            var unit = $("<div class='unit' style='position:absolute'></div>");
            unit.appendTo('#container', {left: });
        }
    }
});

If you are attempting to create a grid matrix with a nested loop, keep in mind that the current code will not generate an X by Y grid effectively due to floating and collapsing of HTML elements. To create a proper grid, specify the X and Y positions using absolute positioning styles and multiply the count by the div width. However, depending on your specific needs, filling up the main container without these adjustments might also work for you.

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

What is the best way to insert a carousel inside a dynamic div that has an image backdrop?

I am facing an issue with placing my carousel within a specified location in a div. I have a responsive div containing an image, and I want the carousel to display at the bottom of the image within the same div. Currently, the carousel appears below the di ...

Clicking on the Upload button suddenly stops working without any indication

Utilizing angular-selenium-protractor, the Upload button initiates the file upload process through flow.js with ngclick as the executor button. When an internally formatted invalid JSON file is selected, under Protractor, the Upload button stops functioni ...

ReactJS: implementing conditional rendering using 'if else' statements in components

I'm currently facing an issue with a seemingly simple goal. For the react show page, my aim is to have an unordered list of the student's instrument sections under the "Instrument Section(s)" heading, which is relatively straightforward. I am ab ...

What is the method for assigning a value to a knockout observable using jQuery?

There is a span element present on an HTML page. <span id="Amount" value="<?php echo $userProvidedAmount ; ?>"></span> Within my knockout code, I am attempting to incorporate this value into an observable using jQuery. However, despite ...

View the picture in a web browser

Currently, I am faced with the challenge of displaying an image that is stored in an MSSQL database created by another person. The column was originally of type IMAGE, but I converted it to varbinary(MAX) using Sequelize. Although I lost some data during ...

Click on link after animation has finished

I'm currently facing an issue with my script not functioning correctly. The code I'm utilizing is from a resource provided by Codyhouse to implement a 3D rotating navigation menu on my webpage. Essentially, when you click the hamburger icon, it o ...

creating drawings that are not restricted by scale on the canvas of html5

I was pondering the possibility of this scenario: imagine you are using a drawing application that operates utilizing HTML5 canvas... if, for example, you draw some lines and squiggles. would it be feasible to later scale the image as if it were a vector ...

Is Asp.net 4 resetting the array with every new run?

I have developed a basic asp.net web page to generate HTML content. The concept is to store previous user inputs in an array each time they click a button, and display them along with the most recent input. However, I encountered an issue where the array a ...

Modifying the ajax POST data for a subsequent request by utilizing .done() instead of success

I find myself in a bit of a puzzle here. I have developed several Ajax functions that trigger one another sequentially upon receiving a valid success response from the previous one. For example... (I have excluded extensive portions of the code that vali ...

How can you determine the index of a table column in JavaScript when you only know its class name?

I am looking for a way to dynamically hide/show table columns based on their classes, without having to add classes to each individual <td> element. This should be accomplished using classes on the columns themselves. Here is a sample of the table ...

"Enhancing HTML table rows using jQuery for a dynamic user experience

I'm currently using a jQuery script to determine the number of rows in a table and then display that count within a <td> tag. <tr> <td id = "jquery"> </td> <td> <%= f.text_field :data1 %> </td> <td ...

JavaScript: Use onclick events to change the class of a div on multiple divs

I have a jQuery script that allows for toggling of the parent class when #icon is clicked. Additionally, when the body is clicked, it reverts back to the original class. Now, I'm looking to achieve the same behavior when clicking on #item5 or #item4 a ...

Tips for arranging a multidimensional array alphabetically by name

var products = [ { "id": 376, "name": "b" }, { "id": 253, "name": "f" }, { "id": 236, "name": "c" }, { "id": 235, "name": "e" }, { "id": 165, ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

The most effective method for transforming an array into an object in JavaScript using a prefixed value as the key

I am working with an array that contains prefix values ["options_a", "options_b", "options_c", "capable_d", "capable_e_c" ] I am looking for a way to transform this array into an object format with the pre ...

The functionality of scope.$observe is unavailable within an AngularJS Directive

Consider the snippet below: appDirectives.directive('drFadeHighlight', ['$animate', '$timeout', function ($animate, $timeout) { return { scope: { isWatchObject: '=' }, restric ...

An error is being thrown by SetState when included within componentDidmount

I am currently learning React JS and have started working on a small application using it. I'm encountering an issue with the SetState method inside the componentDidMount lifecycle method. The scenario is that I have a parent/home component, which ca ...

Objects loaded with ThreeJS GLTF may unexpectedly vanish upon completion

There’s a function in my code that loads a gltf object and adds the mesh to the scene. Inside the gltf load call, I can traverse or getobjectbyname without any issues. However, once outside of the gltf load call, the objects seem to disappear completely. ...

Is there a way to insert a button within a table that will allow me to easily insert new rows and columns?

<head> No content available at the moment. <!-- Here is my code --> <h1>Reserve Your Hall Form</h1> <form class="form-horizontal"> <table class="form-group table table-bordered table-hover"> ...

Elements with a lower z-index do not have text drawn over them

I am currently facing an issue with a hidden list on a page that is crucial for my menu. Despite setting the z-index of different elements, the text inside a specific div only displays to one side which is causing alignment issues. Using display:none is no ...