create an HTML element using JavaScript to display a box with dimensions of n

I am attempting to create a grid in an HTML document using only plain JavaScript. The idea is to take a number from a URL and use that as the basis for generating the grid.

For example, if my URL looks like this: abc.html?num=5, then I would need to create a grid of size 5x5 based on the parameter num=5.

Currently, I am achieving this with jQuery, but I want to explore how it can be done using plain JavaScript. You can view a working example on jsfiddle.

Here is the full content of my abc.html file:

<!DOCTYPE html>
<html>

    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                var defaultNum = 4;
                var url = window.location.search;
                var num = parseInt(url.split('num=')[1]) || defaultNum;
                var container = $('#container');
                var width = container.outerWidth();
                createGrid(num);

                function createGrid(n) {
                    if (!$.isNumeric(n) || n <= 0) return;
                    for (var i = 0; i < n * n; i++) {
                        var dimension = width / n;
                        var cell = $('<div/>').addClass('gridCell').css({
                            'width': dimension + 'px',
                                'height': dimension + 'px'
                        });
                        container.append(cell);
                    }
                }
            });
        </script>
        <style>
            #container {
                width: 300px;
                height: 300px;
            }
            #container > .gridCell {
                float: left;
                padding: 0;
                margin: 0;
                border: 0;
                outline: 1px solid;
            }
        </style>
    </head>

    <body>
        <div id="container"></div>
    </body>

</html>

I am interested in finding out how to achieve the same functionality without relying on libraries like jQuery. How can I accomplish this using plain JavaScript?

Answer №1

To demonstrate this concept, it cannot be achieved in a jsfiddle due to the need for access to the URL. However, you can try out the code by placing it in an HTML file:

<html>
<style>
#container {
    width: 300px;
    height: 300px;
}
#container > .gridCell {
    float: left;
    padding: 0;
    margin: 0;
    border: 0;
    outline: 1px solid;
}
</style>
<body>
<div id="container">
    
</div>

<script>
// QueryString is the function that retrieves the num parameter.
// Function source: http://stackoverflow.com/questions/979975/how-to-get-the-value-from-the-url-parameter
var QueryString = function () {
    // This function is anonymous, executed immediately, and 
    // the returned value is assigned to QueryString!
    var query_string = {};
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
            // First entry with this name
        if (typeof query_string[pair[0]] === "undefined") {
            query_string[pair[0]] = pair[1];
            // Second entry with this name
        } else if (typeof query_string[pair[0]] === "string") {
            var arr = [ query_string[pair[0]], pair[1] ];
            query_string[pair[0]] = arr;
            // Third or later entry with this name
        } else {
            query_string[pair[0]].push(pair[1]);
        }
    } 
        return query_string;
} ();

var defaultNum = 3;
var num = parseInt(QueryString.num) || defaultNum;
var container = document.getElementById('container');
var width = container.offsetWidth;
createGrid(num);

function createGrid(n) {
    // If n is not a number or smaller than 0
    if(isNaN(n) || n <= 0)
        return;
    for(var i = 0; i < n*n; i++) {
        var dimension = width/n;
        var cell = document.createElement('div');
        cell.className = cell.className + ' gridCell';
        cell.style.width = dimension + 'px';
        cell.style.height = dimension + 'px';
        container.appendChild(cell);
    }
}
</script>
</body>
</html>

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

Issues with the count up functionality in jQuery

I'm currently working on a project involving countups. My aim is to have multiple countups displayed on a single page. While having one countup using interval() function poses no issues, I encounter trouble when trying to display two or more countups ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

Dim the brightness of an image on Internet Explorer

I discovered this code on another site and it functions flawlessly in Chrome and FF, however, IE (version 11.0.9) doesn't seem to like it. -webkit-filter: grayscale(0%); -moz-filter: grayscale(0%); -o-filter: grayscale(0%); filter: grayscale(0%); fil ...

Adding existing tags to Select2 in Angular2 can be accomplished by following these steps:

HTML: <select data-placeholder="Skill List" style="width:100%;" class="chzn-select form-control" multiple="multiple"> <option *ngFor="#skill of allSkills" [ngValue]="skill">{{skill}} </option> </select> TS: allSkills = [& ...

Issue with Semantic-UI Special PopUp not displaying on screen

I'm currently working on creating a unique pop-up feature using custom HTML, with the intention of adding content to it later on. My console is displaying the following message: Popup: No visible position could be found for the popup. $(document) ...

Ways to retrieve a variable from a separate TypeScript document

A scenario arises where a TypeScript script contains a variable called enlightenFilters$: import { Component, Input, OnInit } from "@angular/core"; import { ConfigType, LisaConfig } from "app/enrichment/models/lisa/configuration.model"; ...

attach an event listener for the click event

I have a button set up like this Inside index.html: <body> <section> <button id="open-file">Open File</button> ...(series of other similar buttons)... </section> </body> <script> requir ...

Looking for CSS properties to personalize a dropdown list in an HTML select element

After spending several days scouring the internet and trying out numerous methods, I have yet to find a satisfying way to create my own dropdown list. Using CSS, I am able to customize the text color (A), the border style and color (B) of the dropdown fie ...

Server-side rendering with the Node.js mustache template engine

I am in the process of developing a basic application for compiling mustache templates into static pages on the server side. This is what I have accomplished so far: var view = { title: "Joe", calc: function () { return 2+4; } }; v ...

Modify the text when clicked on, but do not change the span

I'm currently attempting to change the text within an anchor (<a href=>) element when another element is clicked. The structure of the HTML is as follows: <h1> <a href=""> replace this text <span class="breadcrumb" ...

Emphasize the Jqgrid row when clicked on, but do not check the multiselect checkbox

Is there a method in jQgrid to highlight a row when clicked without selecting the multiselect checkbox? I attempted using Multiboxonly = true as suggested by Oleg on Your assistance would be greatly appreciated, as this issue is currently hindering progr ...

Ways to verify when leaving the webpage

After spending an excessive amount of time searching for this information, I finally figured it out. So here you have it, I'm sharing the steps to create a custom "ARE YOU SURE YOU WANT TO LEAVE THIS PAGE?" dialog. ...

Creating a photo grid with consistent order is simple using flexbox

I'm currently working on an image grid that consists of 2 rows laid out horizontally. Initially, the first row contains 4 images while the second row has 2 images. Users should have the ability to add more images to the second row. The issue I am faci ...

Display in Google Chrome without any dialogues

Hello friends, I am currently working on adding a print button to my website. I am testing it in Chrome and would like the page to be printed directly without showing any dialog boxes. However, I am facing some difficulties with this process. If anyone has ...

Vue.js: SCSS @import being overlooked

I've found great success using VueJS in two different projects. As I prepare to launch these projects, I'm encountering an issue when generating the files with npm run build. One project, created recently, is working fine. However, the other pro ...

NodeJS Express Application Error: Unable to access /url

I've been troubleshooting this issue for an hour now and I'm stumped. I can't seem to access the specified URL. I created a NodeJs Express app, but when I try to access http://localhost:3000/users/login, I receive the error message Cannot GE ...

CSS styles may not be consistently displayed or may vanish after being initially implemented

The colors and background remain unchanged. In previous projects, everything ended up falling apart Refreshing the page with F5 or CTRL + F5 does not make a difference. When using Open Live Server in VS Code, it initially shows the changes being applied b ...

Retrieve the PDF document from the AJAX call and save it as a

My goal is to have the browser automatically download a PDF file that is received from an AJAX response. After reading about how to download a PDF file using jQuery AJAX, I attempted to simulate a click/download event in this way: var req = new XMLHt ...

The process of loading the Facebook like script using $.getScript is causing an issue where the

How can I make the Facebook like button display properly on my HTML page? I have successfully loaded scripts and divs for Twitter, Google +1 buttons, but the Facebook like button script is not displaying the button. The alert shows that the script is exec ...

Tips for remaining on the current page after sending a post request using Express

I have a simple question that I haven't been able to find a satisfactory solution for. I've created a post route using express, like this: app.post('/search', function(req, res){ // Code to extract data from req and save it to the d ...