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?