Javascript function failing to iterate through a FOR loop

The other day, I reached out here for assistance in creating a grid of squares using JavaScript and CSS.

Someone very helpful provided me with guidance on utilizing two nested for loops and the createElement('div'); method to achieve my goal. However, the example they shared was a code snippet that directly implemented this solution: http://jsfiddle.net/3x1kmcme/

I was looking to trigger this action upon a user click event by utilizing the .click() function from JQuery. Unfortunately, this approach is not working as expected, and I'm not receiving any error messages. I've thoroughly reviewed the code, made some changes, pre-declared variables, and meticulously checked each line, but it seems like the FOR loop isn't being entered. I could be mistaken, though.

Am I overlooking something obvious?

var rows = 8,
    cells = 8,
    count = 0;

var i, j,
    top = 0,
    left = 0;

var boxWidth = 50,
    boxHeight = 50;    

var $canvas = $('#canvas');
var $fragment = $(document.createDocumentFragment());

$(document).ready(function () {
    "use strict";
    $("#btnstart").click(function () {
        function addBox(opts) {
            var div = document.createElement('div');
            div.id = opts.id;
            div.className = 'alive';
            div.style.top = opts.top + "px";
            div.style.left = opts.left + "px";
            $fragment.append(div);

        }
        for (j = 0; j < rows; j += 1) {
            top = j * boxHeight;
            for (i = 0; i < cells; i += 1) {
                count += 1;
                addBox({
                    count: count,
                    id: 'item' + i,
                    top: top,
                    left: i * boxWidth
                });
            }
        }
        $canvas.html($fragment);
    });
});

Answer №1

If you want to see it in action, check out this code snippet

Uncertain about what the issue might be. I made some modifications to the HTML code:

<div id="canvas"></div>

<input type='button' id='btnstart' value='Start' />

Answer №2

After some investigation, I was able to identify the issue and understand why it functioned correctly on JSFiddle. Despite encapsulating the JavaScript file within a Document.Ready function, I discovered that placing the scripts at the bottom of the page, right below the tag, was essential for proper execution.

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 causing the first click of the print button to return null values, but the second click returns the correct values?

Why does the print button show null values the first time it's clicked, but shows exact values the second time using jQuery? Here is the code for my function, can someone please help me with this? function PrevSchdcreateID() { $("#tblPrevSchdc ...

Add an image using ajax in a Django web application

Having encountered an issue within my Django application, I find myself stuck. Despite implementing an Ajax function for uploading a single image to a model, I have yet to achieve success in this endeavor. The problem lies in the fact that although I am ab ...

Ways to avoid Parents Click Event from triggering during a Child's (Grandchild's) click event

My parent div has a unique feature where clicking on it reveals one of the child divs, and clicking again toggles the visibility of the child div. Inside this child div, there is a switch toggle that functions as a hidden checkbox. The issue I'm facin ...

Efficient workflow management using package-lock.json

Currently, my team and I are collaborating on an npm project at work which has dependencies on 'lodash' and 'jquery'. After running '>npm install' to fetch the dependencies and bundling the project, a 'package-lock.js ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

I'm curious about the specific sequence of CSS properties order recommended by Stylelint. Where can I locate

With Stylelint's CSS order option enabled, I'm having trouble getting Visual Studio Code to display the errors. Where can I locate the declaration/property order being used? Below is a snippet of my .stylelintrc.js configuration file: module.exp ...

Issues with authenticating PHP password against MYSQL

I've hit a roadblock while working on my project, and I believe it's a simple fix. However, I just can't seem to figure it out. If you want to see the issue for yourself, check out the live site at www.thriftstoresa.com. The problem lies wi ...

Tips for locating the differences between object keys nested within an array

Imagine having 3 objects, each with a "cost" key that contains an array of objects. The goal is to create a new object called "main" where the "value" in each item will be the difference between its value and the values of other objects. const main = { ...

Ways to style a div identifier within a div group

<div class="content"> <div class ="imgs"> <a href="#"><img src="images" alt="some_text" width="250" height="210"></a> </div> <div class = "compu"> <div id="titulo">text</br></div> ...

Is it possible to dynamically retrieve an element's style from @ViewChild in an Angular 2 component without needing an active approach?

For instance, there's an element in the template that uses a local variable #targetElement to retrieve its current width whenever needed. However, I prefer not to calculate the style programmatically. I attempted using a setter with the @ViewChild ann ...

Steps on obtaining the jqwidget grid filter input field

I am currently working with the jqwidget grid (jqxgrid) and I need to retrieve the object of the Filter textbox. Visit this link for the jqwidget grid Anyone able to assist me in retrieving the filter object for the name textbox? Thank you in advance. ...

implement adding a division element to the DOM using the append

I am facing an issue with this particular code. The intended functionality is to create multiple divs in a loop, but it seems to be dysfunctional at the moment. Upon clicking, only one div appears and subsequent clicks don't trigger any response. < ...

A JButton named "action" with HTML styling and a specific keyboard shortcut

My JButton is created with an Action that contains HTML in its name. To set the mnemonic on the JButton, I first need to extract the first character from the name by parsing out the HTML tags. For instance, if the JButton name is "Test Button", after re ...

Display the bash script results on an HTML webpage

My bash script fetches device status and packet loss information, slightly adjusted for privacy: #!/bin/bash TSTAMP=$(date +'%Y-%m-%d %H:%M') device1=`ping -c 1 100.1.0.2 | grep packet | awk '{ print $6 " " $7 " " $8 }'` device2=`pin ...

Attention: Issue with 'className did not match' error in react-material-ui-carousel

I am currently utilizing React, NextJS, and Material UI in my project I recently integrated the react-material-ui-carousel package, but encountered the following error: Warning: Prop className did not match. Server: "MuiButtonBase-root MuiIconButton ...

Tips for accessing a parent object function in NodeJS modules

Currently, I am developing a nodejs module to manage all SQL operations for a project. However, I've encountered an issue related to the language as there is no parent relation in JavaScript. If I duplicate my connection, I end up with a handshake err ...

Unable to leverage the most recent iteration of three js

Having trouble using the newest version of three.js (r102) in IE. I keep getting an ImageBitMap error (ImageBitMap is not defined). Any tips on how to solve this would be greatly appreciated. Thanks! ...

Validating if a specific criterion is met by any Document in Mongoose Library using JavaScript

I'm currently exploring a method to run through documents and utilize the .find method to verify if there is a Document that satisfies certain conditions. Here's an example: //example model const example = new ExampleModel ({ exampleName : &qu ...

Angular: Transferring dynamic functions between parent and grandchild components

For my angular application, I am developing a versatile table component that can accept inputs for rows, columns, as well as handle various action button functions to render the table. The end result should resemble something like this: https://i.sstatic.n ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...