Functions properly in JSFiddle, but fails in the browser even when surrounded by a document ready handler

I am struggling with printing a 16x16 grid of divs using jQuery. It works perfectly on JSFiddle, but only one row is printed when testing in the browser. I realized that changing the jQuery version from edge to 2.1.3 on JSFiddle results in the same issue in the browser. What could be causing this discrepancy?

Despite finding similar questions, none of the suggested solutions have worked for me. I have tried using window.onload, $(document).ready(), replacing $ with jQuery, and adjusting the script linking location without success. If anyone can point out where my code is failing or direct me to a relevant solution, I would greatly appreciate it.

JQuery

$square = $('<td><div class="square"></div></td>');

$(document).ready(function () {
    for (var i = 1; i <= 16; i++) {
        for (var j = 1; j <= 16; j++) {
            $("#contain").append("<td></td>");
        }
        $("#contain").append("<tr></tr>");

    }
    $square.appendTo("td");
});

HTML

<!doctype html>
<html>
    <head>
        <title>Game</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <link type="text/css" rel="stylesheet" href="gamecss.css"/>
        <script type="text/javascript" src="gamejs.js"></script>
    </head>
    <body>
        <table id="contain"></table>
    </body>
</html>

CSS

#contain
{
    width:100%;
}
.square
{
    height: 20px;
    width: 20px;
    background-color: black;
    border: solid 1px black;
    display: block;
}

Answer №1

To enhance the functionality, I suggest modifying the JavaScript code to dynamically add a new column td to the last row tr of the table contain.

$square = $('<td><div class = "square"></div></td>');
$(document).ready(function () {
    for (var i = 1; i <= 16; i++) {
        for (var j = 1; j <= 16; j++) {
            $("#contain tr").last().append("<td></td>");
        }
        $("#contain").append("<tr></tr>");

    }
    
    $square.appendTo("td");
});
#contain
{
    width:100%;
}
.square
{
    height: 20px;
    width: 20px;
    background-color: black;
    border: solid 1px black;
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

    <body>
        <table id = "contain"></table>
    </body>

Answer №2

For adding your JavaScript code, simply insert it within the body tags using

<script>....JS Code...</script>
.

Your HTML File

<!doctype html>
<html>
    <head>
        <title>Game</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
        <link type="text/css" rel="stylesheet" href="gamecss.css"/>
        <script type="text/javascript" src="gamejs.js"></script>
        <style>
        #contain
        {
            width:100%;
        }
        .square
        {
            height: 20px;
            width: 20px;
            background-color: black;
            border: solid 1px black;
            display: block;
        }
        </style>
    </head>
    <body>
        <table id = "contain"></table>

        <script>
        $square = $('<td><div class = "square"></div></td>');
        $(document).ready(function () {
            for (var i = 1; i <= 16; i++) {
                for (var j = 1; j <= 16; j++) {
                    $("#contain").append("<td></td>");
                }
                $("#contain").append("<tr></tr>");

            }
            $square.appendTo("td");
        });
        </script>
    </body>
</html>

To see the result, copy the above code and create an HTML file with it. Run the file to see the outcome of your coding.

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 eliminate the border on an image input button?

Here is the code I've been working on: HTML: <!DOCTYPE html> ... <form> <input type="image" value=" " class="btnimage" /> </form> ... CSS: .btnimage { width: 80px; height: 25px; background:url('C:/Users ...

The lifespan of an Angular controller and its management of events

What is the best way to manage events, such as $rootScope or socket events, in an Angular controller without causing issues with event duplication? I have noticed that my controllers are not being destroyed properly, leading to problems when it comes to li ...

Adding the active class in Bootstrap can be easily achieved in CodeIgniter by using the

I am seeking guidance on how to add an active class in CodeIgniter when dividing the view into three separate files. These files include: header.php page1.php ... page10.php footer.php According to this thread, there seems to be no clear solution prov ...

Converting a JSON array into an object representation

I have received some JSON data that has a specific structure: [ { "items": [ { "id": "xxxx", "description": { "style": "", "specs": "" } }, { "id": ...

Extract form input to utilize in nodemailer

Currently I am working on a form implementation where I intend to utilize nodemailer for sending test emails to myself. My goal is to have the email inputted into the form dynamically appear in both the "to" and "subject" fields when the user submits the f ...

Creating two full-height columns in Twitter Bootstrap 4 without the need for scrolling

I'm attempting to create a two-column full-height layout using bootstrap 4. My goal is to achieve the following structure: +-------------------------------------------------+ | Logo Header Another Logo| - height 10 % +--- ...

I'm having trouble viewing my display:table-cell content because Internet Explorer is hiding it

I am attempting to align an icon vertically centered and far right inside a container. I currently have code that achieves this using ::after and table-cell properties. However, the content does not display in Internet Explorer. If I remove the display:tab ...

Triggering the 'change' event on a hidden value in jQuery can cause issues with knockout dependent observables

Let me share the story of how we stumbled upon this issue... Basically, we were invoking trigger('change') on all our form inputs to notify other knockout observables that their values had been reset. However, we suspect it could be a bug in Knoc ...

Ways to remove the address bar from a mobile browser like Chrome or an Android browser

Is there a way to make videojs go full screen on Android devices when the URL is entered, without displaying the address bar? ...

Discovering Unnecessary CSS & JS Code

Currently, I am tackling a freelance project focused on upgrading a website. The client is requesting specific features from their old site be replicated on the new one. However, the challenge lies in the fact that the old site's CSS and JS are consol ...

What is the process of embedding a jquery function within a javascript function?

I'm currently using Javascript to validate my form, but I'd prefer to show the errors with Jquery. Is it possible to accomplish this? ...

Extracting information from a website with C#

Hey everyone, I am looking to extract specific table data from a webpage instead of retrieving all the information. For instance, take a look at the URL provided below. There are multiple tables on the webpage. Can someone please provide me with a soluti ...

What could be causing the data storage issue in the state?

Using axios, I am fetching data and storing it in a state variable useEffect(() => { getCartItems(); }, []); const [abc, setAbc] = useState([]); const getCartItems = async () => { let data = await CartApi.get(`/${store.getState().auth.user.id}/ ...

Create a hierarchical tree structure using a string separated by dots

I am struggling with organizing a tree structure. :( My goal is to create a tree structure based on the interface below. export type Tree = Array<TreeNode>; export interface TreeNode { label: string; type: 'folder' | 'file'; ...

How to send data from JavaScript to ASP.NET

$(document).ready(function () { $("#MainContent_ddlFieldName").on("change", function () { var id = $(this).val(); var name = $(this + "option:selected").text(); $('#<%= lblValue.ClientID %> ...

Communication Between Directives in AngularJS

Recently, I've been working on a custom filter directive in Angular: app.directive('filter', function(){ return { restrict: 'E', transclude: true, scope: { callFunc: '&' }, template: ...

What is the best way to access the width of the top-level parent div and adjust the widths of its child and parent divs according

I'm currently working on creating a custom directive in Angular 4 to enable resizing of a div. Here's the HTML code snippet: <div class="super-parent"> <div class="parent"> My Div content <div class="child" re ...

The function str.split() is dividing the text based on individual letters rather than the specified delimiter

I am facing an issue where the string of tags retrieved from firebase needs to be split by ',' and stored in the data() for rendering. The firebase snapshot data is correctly formatted after splitting when viewed in the console like this: "t ...

Overlap with upper picture formatting

I've been struggling to create an ion-card with two images: a main picture and a small book cover. Any ideas on how to achieve this? Note: The layout should have 2 images, one at the top and another as a small book cover. Check out this sample on St ...

Exploring the world of AngularJS and Packery

After stumbling upon this particular question, I was thrilled to find the perfect answer that suits my needs. Now I am seeking guidance on how to implement the solution provided in this question. Is there a way to make the necessary changes for utilizing n ...