Develop interactive div elements with the help of JavaScript/jQuery

Exploring dynamic div creation using javascript or jquery and looking for guidance.

<div id="clickable">
    <button class="start">Default</button>
    <button class="random">Randon</button>
    <button class="gradient">Gradient</button>
    <button class="trail">Trail</button>
    <button class="clear">Clear</button>
    <div id="start">Please click on one of the buttons to get started!</div>
</div>

<div class="wrapper">

</div>

Looking to insert x*x divs into the "wrapper" class. For instance, entering 4 would generate a 4x4 grid of divs. Appreciate your help!

The current code is not functioning as expected.

$(".start").click(function() {
    total = prompt("Please enter a number");
});

$(document).ready(function() {
    $(".start").click(function() {
        function begin(total) {
            for (var i = 0; i < total; i++) {
                var rows = document.createElement("div");
                    for (var i = 1; i < rows; i++) {
                        var columns = document.createElement("div");
                    }
            }
        }
    });    
});

Answer №1

Take a look at this example in the fiddle provided to give you a head start.

To dynamically create divs, you need to follow these steps: Find the container element by using $(".wrapper")

The grid structure I implemented treats each row as a single div (with 'n' rows) and each row contains 'n' column divs.

To generate a div, make use of the convenient $('<div>', {...}) method. Remember to append it to the container within the loop.

All styling should be done in CSS, which is demonstrated in the provided fiddle.

You can refer to the code below for guidance.

$(".start").click(function () {
    total = prompt("Please enter a number");
    console.log("Total is", total);
    //Call the function to create the grid.
    createGrid(total);
});

function createGrid(total) {
    //Get the wrapper element.
    var $container = $(".wrapper");

    //Iterate through each row.
    for (var rowIndex = 0; rowIndex < total; rowIndex++) {

        //Create the framework for the row
        var rowId = "row-" + rowIndex;
        var $row = $("<div>", {
            "class": "row",
            "id": rowId
        });

        //Iterate through each column.
        for (var columnIndex = 0; columnIndex < total; columnIndex++) {

            //Create the framework for the column (Ensure unique IDs)
            var columnId = rowIndex + "-col-" + columnIndex;
            var $column = $("<div>", {
                "class": "column",
                "id": columnId
            });

            //Append the column to the row div.
            $row.append($column);

        }

        //Append the completed row to the container.
        $container.append($row);
    }
}

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

Having trouble with the collapse feature on my DataList cards

I have a sample card and a DataList on my webpage. The collapse functionality is functioning correctly on the example card, but I am unable to get it to work on the actual cards. Below is the code snippet for reference: <div class="resultadosEspe ...

``There appears to be an issue with the functionality of the jQuery

I've been experimenting with using AJAX in a PHP form, but for some reason it's not working as expected. I'm at a loss trying to figure out why. Here is my code: <!DOCTYPE html> <html lang="es"> <head> <title>< ...

Issue with Vue2: DIV does not adjust height when using v-for loop

I have a div set up like: <div class="pt-4"> <h5>Genres:</h5> <div class="inline-block float-left" v-for="(genre, index) in moreData.genres" :key="index"> <span v-if="index < ...

What steps can be taken to resolve the Angular error stating that the property 'bankCode' is not found on type 'User' while attempting to bind it to ng model?

I'm encountering an issue with my application involving fetching values from MongoDB and displaying them in an Angular table. I've created a user class with properties like name and password, but I keep getting errors saying that the property doe ...

Tips for executing gulp tasks in the command line

As a newcomer to Gulp, I've encountered an issue with executing a task named task1 in my gulp.js file. When I enter "gulp task1" in the command line, it opens the gulp.js file in Brackets editor instead of running the task as expected. Can anyone offe ...

A method for displaying monthly data in a single row

Hey there! I'm currently dealing with a data list stored in an array. The |arraycontains various objects` each with their own properties such as name, created-at, and more. My goal is to display all users who were created within a specific month in on ...

Do you know the method to make a Youtube iframe go fullscreen?

I am encountering an issue with developing an iframe where I am unable to make it go fullscreen from within the iframe. Fullscreen API works when both the iframe and hosting website are on the same domain, as well as triggering fullscreen from outside the ...

The command is failing to include functionality with the yarg npm package

I have been attempting to incorporate a command using yargs, however, after executing my code, the command does not seem to be added successfully. Below is the snippet of what I am attempting: const yargs = require('yargs') //create add command ...

Using the clientWidth property in React

While I have a solid background in Javascript, I am relatively new to working with React. In my previous projects where I coded directly in javascript for the browser, I frequently used the following code snippet: width = document.getElementById('elem ...

Converting two adjacent columns in Bootstrap 5 into two rows on smaller screens: a step-by-step guide

I have recently started using Bootstrap for a project and I want to ensure that my application is responsive on various device screens including normal laptops, iPad Mini (768 X 1024), and iPad Air (820 X 1180). Below is a snippet of my HTML code: <div ...

I am interested in creating a class that will produce functions as its instances

Looking to create a TypeScript class with instances that act as functions? More specifically, each function in the class should return an HTMLelement. Here's an example of what I'm aiming for: function generateDiv() { const div = document.crea ...

What is the best method for storing pug-formatted data in a database?

I am currently developing a JavaScript application where I utilize pug for templates and diskdb for storing data. Within my content, I have implemented pug syntax which may appear in the following format: p some content here p some more content here p: # ...

Add up the inputs whenever there is a change using jQuery

I'm trying to implement a feature in my code where the price is automatically recalculated every time there is a change. <table class="table table-striped table-bordered listItem"> <tbody> <tr> <th width="20%"> ...

Discovering a way to monitor keyup and keydown occurrences in JavaScript on an iPhone

Looking to track keyup/keydown events in JavaScript on iPhone browsers. My goal is to automatically move the focus to the next form element after the user has inputted the maximum number of characters in a text box. ...

StopDefault and JSON Placement

We have a form that sends data to an external domain using JSONP to avoid cross-domain limitations. Everything is functioning properly except for preventing the default form submission that triggers a page reload. Below is the HTML code for the form: < ...

problem with making ajax requests during the server-side processing of DataTables

Currently tackling server-side processing with datatables, but encountering an ajax error that I'll detail shortly. First things first, here's my code: Table <table id="call_analysis_basic_table" class="display" cellspacing="0" width="100%"& ...

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

Creating a dynamic column template that displays and checks checkboxes conditionally

I am faced with the task of dynamically generating columns on a screen based on values retrieved from a database. I have successfully created Kendo grid columns based on this input. However, these columns need to display checkboxes that are conditionally ...

PHP & Ajax integration for uploading files via a Bootstrap modal dialog

After exploring numerous posts for a solution to my issue without success, I felt the need to seek assistance specific to my problem here. Currently, I am using form elements in a modal. All the form elements successfully submit through my Ajax and store ...

Sending a parameter to a request-promise function within an iteration through a forEach loop

I have successfully implemented an API call for price data. However, I am facing an issue while trying to pass the variable exchange_pair_id into the then() function. Within the forEach loop, the exchange_pair_id is accurate for each asset. But inside the ...