How to populate browser's entire window/document with rectangles - javascript

I want to populate the entire window with rectangles, no matter what size of window it is. eg. If rectangles are 250px wide, and window is 1000px wide, then it shold be 4 rec. in one row. I managed to fill just one row. Here is the code below
<!DOCTYPE HTML>
<html>
<head>
<style>
div {
width: 250px;
height: 150px;
border: 1px solid black;
border-collapse: collapse;
display: block;
position: fixed;
}
</style>
<script>
function ubaci_div() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}
</script>
</head>
<body id="body">
<p id="p" onclick="ubaci_div()">Klikni</p>
</body>
</html>

I think you are asking for something like this?
https://jsfiddle.net/DIRTY_SMITH/cfckvvzw/9/
function ubaci_div() {
var i = 0;
var h = window.innerHeight;
var num = (h / 150);
for (i = 0; i < num; i++) {
alert(num);
loop();
var br = document.createElement('br');
}
}
function loop() {
var sto = 0;
var ipsilon = "px";
for (var x = 0; sto < window.innerWidth - 250; x++) {
var cet = sto + ipsilon;
var divovi = document.createElement("DIV");
document.getElementById("body").appendChild(divovi);
document.getElementsByTagName("DIV")[x].setAttribute("id", "id1");
document.getElementsByTagName("DIV")[x].style.left = cet;
sto += 250;
}
}

Something like this?
JSFiddle: https://jsfiddle.net/vc7w608m/
var rectangleWidth = 250;
var rectangleHeight = 100;
var columnCount = Math.ceil(window.innerWidth / rectangleWidth);
var rowCount = Math.ceil(window.innerHeight / rectangleHeight);
console.log(columnCount, rowCount)
for (var rowIndex = 0; rowIndex < rowCount; rowIndex++) {
var rowDiv = document.createElement("div");
rowDiv.style.height = rectangleHeight + "px";
rowDiv.style["white-space"] = "nowrap";
rowDiv.style["overflow"] = "hidden";
document.body.appendChild(rowDiv);
for (var columnIndex = 0; columnIndex < columnCount; columnIndex++) {
var rectangle = document.createElement("div");
rectangle.style.height = rectangleHeight + "px";
rectangle.style.width = rectangleWidth + "px";
rectangle.style.display = "inline-block";
rectangle.style["background-color"] = "rgb(" + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ", " + (Math.floor(Math.random()*256)) + ")";
rowDiv.appendChild(rectangle);
}
}

Related

Trying to generate 100 boxes but only 2 boxes are displayed?

So I'm only using javascript, html, and css to generate 100 boxes in any random position, this works by using the div with the id container in the html file and then using the javascript file to generate the boxes through a loop making a div for each box then appending it to the container, but the problem is I can see two boxes appearing on screen? here is my code below:
//this is the javascript
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.setAttribute("id", "box");
container.appendChild(box);//o
var bx = document.getElementById("box");
var w=window.innerWidth;
var h=window.innerHeight;
bx.style.right = w * Math.random() + "px";
bx.style.top = h * Math.random() + "px";
}
}
//here is the css
#box
{
background-color: blue;
width: 50px;
height: 50px;
padding: 5px;
position: fixed;
}
//this is the html
<!DOCUTYPE html>
<html lang = "en">
<head>
<link href = "box.css" rel = "stylesheet" type="text/css">
<script src = "box.js" type="text/javascript"></script>
</head>
<body onload="myFunction()">
<div id="container">
</div>
</body>
</html>
Don't get a reference for the box again from the DOM
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.setAttribute("id", "box");
container.appendChild(box);//o
// var bx = document.getElementById("box"); <--- this line is redundant
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
ID's should be unique, instead use a class for each box
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.classList.add("box");
container.appendChild(box);//o
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
So your code in the end becomes:
function myFunction(){
var container = document.getElementById("container");//o
for (var i = 0; i < 100; ++i) {//o
var box = document.createElement("div");//o
box.classList.add("box");
container.appendChild(box);//o
var w=window.innerWidth;
var h=window.innerHeight;
box.style.right = w * Math.random() + "px";
box.style.top = h * Math.random() + "px";
}
}
.box
{
background-color: blue;
width: 50px;
height: 50px;
padding: 5px;
position: fixed;
}
<!DOCTYPE html>
<html lang = "en">
<head>
<link href = "box.css" rel = "stylesheet" type="text/css">
<script src = "box.js" type="text/javascript"></script>
</head>
<body onload="myFunction()">
<div id="container">
</div>
</body>
</html>
Use the name attribute and a data-id attribute to retrieve any elements with an unique id.
Construction:
let container = document.getElementById("container")
for(let count = 1; count < 100; ++count) {
let box = document.createElement("DIV")
box.setAttribute("name", "e")
box.dataset.id = count
container.appendChild(box)
}
HTML result :
<div name="e" data-id="1"></div>
<div name="e" data-id="2"></div>
<div name="e" data-id="3"></div>
<div name="e" data-id="4"></div>
Add a function to retrieve any element with the first occurence of a numbered id.
function getFormRef(name, id) {
let d = document.getElementsByName(name)
let x = Array.prototype.slice.call(d).filter(a => a.dataset.id == id)
return x[0]
}
let first = getFormRef("e", 1)

Colored Squares HTML/Javascript

Here is the current index (HTML and JavaScript):
var maxZ = 1000;
window.onload = function() {
var add = document.getElementById("add");
add.onclick = addSquare;
var colors = document.getElementById("colors");
colors.onclick = changeColors;
var squareCount = parseInt(Math.random() * 21) + 30;
for (var i = 0; i < squareCount; i++) {
addSquare();
}
}
//Generates color
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function addSquare() {
var square = document.createElement("div");
var squareArea = document.getElementById("squareArea");
square.className = "square";
square.style.left = parseInt(Math.random() * 650) + "px";
square.style.top = parseInt(Math.random() * 250) + "px";
square.style.backgroundColor = getRandomColor();
square.onclick = squareClick;
squareArea.appendChild(square);
}
function changeColors() {
var squares = document.querySelectorAll("#squareArea div");
for (i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = getRandomColor();
}
}
function squareClick() {
var oldZ = parseInt(this.style.zIndex);
if (oldZ == maxZ) {
this.parentNode.removeChild(this);
} else {
maxZ++;
this.style.zIndex = maxZ;
}
}
<html>
<head>
<title>Colored Squares</title>
<script src="Squares.js" type="text/javascript"></script>
<link href="Squares.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="squareArea"></div>
<div>
<button id="add">Add Square</button>
<button id="colors">Change Color</button>
</div>
<p>Click a square to move it to the front.</p>
</body>
</html>
Here is the goal:
Edit Colored squares to add the following functionality.
Users will be able to click a square and drag it to any position on the screen. - When the user lets go of the click it will stay in that position.
In order to accomplish this you will need to add Prototype and Scriptaculous to the scripts loaded in the html and use their functionality.
You will also need to create 3 functions in the JavaScript file:
function squareMouseMove(event)
function squareMouseDown(event)
function squareMouseUp(event)
Add appropriate global variables
Change the creation of the squares to added observers for the mouse events that execute the functions.
The issue that you have with your code is that the squares are empty, so they collapse to nothing and you will not see them. Add a width and height to them so you can see them.
Another issue is that you're specifying the left and right, but these properties will have no effect unless you make them absolutely positioned.
Here is your code working with the width, height, and position properties added:
var maxZ = 1000;
window.onload = function() {
var add = document.getElementById("add");
add.onclick = addSquare;
var colors = document.getElementById("colors");
colors.onclick = changeColors;
var squareCount = parseInt(Math.random() * 21) + 30;
for (var i = 0; i < squareCount; i++) {
addSquare();
}
}
//Generates color
function getRandomColor() {
var letters = "0123456789abcdef";
var result = "#";
for (var i = 0; i < 6; i++) {
result += letters.charAt(parseInt(Math.random() * letters.length));
}
return result;
}
function addSquare() {
var square = document.createElement("div");
var squareArea = document.getElementById("squareArea");
square.className = "square";
square.style.left = parseInt(Math.random() * 650) + "px";
square.style.top = parseInt(Math.random() * 250) + "px";
square.style.width = "100px";
square.style.height = "100px";
square.style.position = "absolute";
square.style.backgroundColor = getRandomColor();
square.onclick = squareClick;
squareArea.appendChild(square);
}
function changeColors() {
var squares = document.querySelectorAll("#squareArea div");
for (i = 0; i < squares.length; i++) {
squares[i].style.backgroundColor = getRandomColor();
}
}
function squareClick() {
var oldZ = parseInt(this.style.zIndex);
if (oldZ == maxZ) {
this.parentNode.removeChild(this);
} else {
maxZ++;
this.style.zIndex = maxZ;
}
}
<html>
<head>
<title>Colored Squares</title>
<script src="Squares.js" type="text/javascript"></script>
<link href="Squares.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="squareArea"></div>
<div>
<button id="add">Add Square</button>
<button id="colors">Change Color</button>
</div>
<p>Click a square to move it to the front.</p>
</body>
</html>

Display single image multiple times in a table using JS

I have to make a game in which there is an 8x8 table and a coin displays on them(more than at 10 positions at a time) for 3000milliseconds on different position simultaneously. The coin display should start at a click of "Start" button and it continues for 1minute. My problem is that I am not able to make a random function which generates images randomly on different positions.it is giving some error of appendchild undefined.I want my image to display randomly on different positions),Here what I've tried so far.I've just started learning JS so please don't judge my code & i'm posting this again because i didn't get any response in my previous post.
I had "display:none;" all the coins and i want a random function at multiple positions on which the coins displays block.
PS:I can't use any Jquery and remove the mistakes done previously
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
var tr = tbl.getElementsByTagName("tr")[randomNumber];
var td = tbl.getElementsByTagName("td")[randomNumber];
var img = tbl.getElementById("coin_image");
td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
i don't know exactly what you are looking for but it may works using same id multiple times is not a good choice
<script type="text/javascript">
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image'+i+'">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.createElement('table');
var randomNumber = Math.floor(Math.random() * 7);
//var tr = tbl.getElementsByTagName("tr")[randomNumber];
//var td = tbl.getElementsByTagName("td")[randomNumber];
var img = document.getElementById("coin_image"+randomNumber+"");
//td[randomNumber].appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
I think I could tweak your code:
function tableCreate(){
var body = document.body;
var tbl = document.createElement('table');
tbl.id = 'myTable';
tbl.style.width = '730px';
tbl.style.height = '650px';
tbl.style.border = '4px solid grey';
tbl.style.display = 'inline-block';
for(var i = 0; i < 8; i++){
var tr = tbl.insertRow();
for(var j = 0; j < 8; j++){
var td = tr.insertCell();
var div = document.createElement('div');
td.appendChild(div);
div.innerHTML = '<img src="http://icons.iconarchive.com/icons/awicons/vista-artistic/128/coin-icon.png" alt="coin.png" class="coin_img" id="coin_image">';
td.style.border = '1px solid black';
td.style.width = '85px';
td.style.height = '75px';
td.id = 'r' + i + 'c' + j;
}
}
body.appendChild(tbl);
}
function onTimer() {
var seconds = 60;
function tick() {
var counter = document.getElementById("counter");
seconds--;
counter.innerHTML = "<h1>Time Left:-"+"0:" + (seconds < 10 ? "0" : "") + String(seconds)+"</h1>";
if( seconds > 0 ) {
setTimeout(tick, 1000);
} else {
alert("Game over");
}
}
tick();
setInterval(function(){
var tbl = document.getElementById('myTable');
var randomNumber = Math.floor(Math.random() * 7);
var tr = Array.prototype.slice.call(tbl.getElementsByTagName("tr"))[randomNumber];
var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
var img = document.getElementById("coin_image");
td.appendChild(img);
img.style.display = "block";
}, 3000);
}
function onRestart()
{
location.reload();
}
.button_class
{
float: left;
display: inline-block;
width: 400px;
}
.btn
{
width: 140px;
height: 50px;
margin: 20px;
font-size: 16px;
background-color:
}
.coin_img
{
width: 100%;
height: 70px;
display: none;
}
.counter_div
{
margin-left: 20px;
}
<body onload="tableCreate()">
<div class="button_class">
<button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
<button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
<div class="counter_div" id="counter">
<h1>Total Time:-1:00</h1>
</div>
</div>
</body>
Your inaccuracies:
add an id to the table when you initially create it in function tableCreate() like tbl.id ='myTable';
variable tbl in onTimer() function shoudn't contain a new table but
rather the existing one like var tbl = document.getElementById('myTable');
functions like getElementsByTagName("tr") return HTMLCollections,
not arrays. To convert it into array use
Array.prototype.slice.call(tbl.getElementsByTagName("tr"))
If I am not mistaken, you can call getElementById only on
document, so it should be var img = document.getElementById("coin_image");, not var img =tbl.getElementById("coin_image");
td variable in onTimer's interval already contains the td
element, no need to add an index. So, it should be
td.appendChild(img);
In order to avoid placing all the coins in the same row, change var
td = Array.prototype.slice.call(tbl.getElementsByTagName("td"))[randomNumber];
to var td = Array.prototype.slice.call(tr.getElementsByTagName("td"))[randomNumber];
It makes your code work, but there are some other, lets say, logical problems because the coins do not disappear from the cells. Also they only appear on cells with coordinates like (0,0) (2,2) (4,4) etc. because you generate the random number only once and then use it for both - row and column. I don't know maybe it is what you want. If not, work on it too.

Using jQuery to Generate a Grid of DIVs, but Get Wierd Behavior if it Isn't 10 x 10

I'm using jQuery to generate a grid of divs that I will then style to become the board of a game. It works fine when I set the grid to 10 x 10, but when I increase the number of squares, even by one, the second column from the left either doesn't display at all (although the html is fine), or it extends from the bottom of the grid down instead of up.
I've tried messing with the stylesheet and pretty much every variable in the code to no avail. Any help would be appreciated.
$(document).ready(function() {
var row_count = 11;
var base = document.getElementById('base');
var square = '<div class="square"></div>';
var col_count = 11; // Sets the number of columns
while (col_count >= 0) { //Outer loops controls the columns.
row_count = 11; // sets the number of rows
while (row_count >= 0) {
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
row_count--;
}
col_count--;
}
// These two values, for posx and posy are the positioning
// coordinates for the squares of the grid
var posx = 10;
var posy = 10;
var col = 0; // Initiates the column counter for the below while loop
while (col <= 11) { // must match var col_count above
$.each($('div[id^="in_col_' + col + '"]'), function() {
$(this).css('top', posy);
$(this).css('left', posx);
posy += 41;
});
posy = 10;
posx += 41;
col++;
}
});
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='base'>
</div>
Fiddle of example
I refactored the code a bit, using for loops instead so we don't have to keep track of iteration variables. I also used float: left; on the tiles and clear: both; whenever we want to wrap down to a new line.
Javascript
$(document).ready(function() {
var col_count = 11; //Sets the number of columns
var row_count = 11; //sets the number of rows
var base = $('#base');
var square = '<div class="square"></div>';
for(var i = 0; i < col_count; i++){
for(var j = 0; j < row_count; j++){
var tile = $(square);
if(j === 0) tile.addClass('newRow');
base.append(tile);
}
}
});
CSS
.square {
border: 1px solid black;
height: 40px;
width: 40px;
float: left;
margin-top: -1px;
margin-left: -1px;
}
.newRow {
clear: both;
}
fiddle: https://jsfiddle.net/e0g6y9th/
Problem is in $.each($('div[id^="in_col_' + col + '"]'), function() {
col_10 is called 2 times. Change it to $.each($('div[id^="in_col_' + col + '_"]'), function() {, a more restrictive regex
$(document).ready(function() {
var row_count = 11;
var base = document.getElementById('base');
var square = '<div class="square"></div>';
var col_count = 11; // Sets the number of columns
while (col_count >= 0) { //Outer loops controls the columns.
row_count = 11; // sets the number of rows
while (row_count >= 0) {
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
row_count--;
}
col_count--;
}
// These two values, for posx and posy are the positioning
// coordinates for the squares of the grid
var posx = 10;
var posy = 10;
var col = 0; // Initiates the column counter for the below while loop
while (col <= 11) { // must match var col_count above
$.each($('div[id^="in_col_' + col + '_"]'), function() {
$(this).css('top', posy);
$(this).css('left', posx);
posy += 41;
});
posy = 10;
posx += 41;
col++;
}
});
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='base'>
</div>
The selector in your $.each loop is matching columns multiple times. A simple solution will be to zero-pad the numbers in your ids:
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
Then change
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count + '"></div>', {
"class": "square"
}).appendTo('#base');
To
$('<div class="square" id = "in_col' + '_' + pad(col_count,3) + '_' + pad(row_count,3) + '"></div>', {
"class": "square"
}).appendTo('#base');
And
$.each($('div[id^="in_col_' + col + '"]'), function() {
to
$.each($('div[id^="in_col_' + pad(col,3) + '"]'), function() {
Here's a working fiddle: https://jsfiddle.net/xc9gyv8p/4/
Here's my take
fiddle
$(document).ready(function() {
var row_count = 11;
var col_count = 11;
var x = 0;
var y = 0;
var offX = 41;
var offY = 41;
for(var i = 0; i < col_count; i++){
$('#base').append('<div id="col_'+i+'" class="col" style="left:'+x+'px"><div>');
x += offX;
y = 0;
for(var j = 0; j < row_count; j++){
$('#col_'+i).append('<div class="square" id="row_'+j+'" style="top:'+y+'px"></div>');
y += offY;
}
}
});
.col{
position: absolute;
}
.square {
border: 1px solid black;
height: 40px;
width: 40px;
position: absolute;
}
Yours is more a mathematical problem. My version is much easier to understand, here is a fiddle.
go row by row and column by column in each row. so var i is each row and var j is each column in the row (starting every time by 1 and count up till reach var col_count.
$(document).ready(function() {
var row_count = 11;
var col_count = 11;
var size = 41;
var base = document.getElementById('base');
for (var i=1; i<=row_count; i++) {
for (var j=1; j<=col_count; j++) {
$('<div class="square" id = "in_col' + '_' + j + '_' + i + '"></div>')
.addClass('square')
.css({
'left': j*size,
'top': i*size
})
.appendTo('#base');
}
}
});
to select each elements in column 1 use div[id^="in_col_1_"]. I would recommend you to work with data attributes by changing the code to:
$(document).ready(function() {
var row_count = 11;
var col_count = 11;
var size = 41;
var base = document.getElementById('base');
for (var i=1; i<=row_count; i++) {
for (var j=1; j<=col_count; j++) {
$('<div class="square" id = "in_col' + '_' + j + '_' + i + '"></div>')
.addClass('square')
.attr('data-col', j)
.attr('data-row', i)
.css({
'left': j*size,
'top': i*size
})
.appendTo('#base');
}
}
});
so you can easily select elements in row 1 by div[data-row="1"] and column 1 by div[data-col="1"]. Have a look at this fiddle.
insted for running while loop backward run it forward, it will fix your problem
var row_count = 0;
var col_count = 0; // Sets the number of columns
while (col_count <= 10){ //Outer loops controls the columns.
row_count = 0; // sets the number of rows
while (row_count <= 10) { // Inner loop controls the cells in each column.
$('<div class="square" id = "in_col' + '_' + col_count + '_' + row_count +'"></div>', {"class":"square"}).appendTo('#base');
row_count++;
}
col_count++;
}
IrkenInvader, thanks, I went with your solution, much cleaner than what I had originally and obviates the need for the bit of code (the regex in the jQuery selector) that was causing the problem.
$(document).ready(function(){
var col_count = 11;// Sets the number of columns
var row_count = 11; //sets the number of rows
var base = $('#base');
for(var i = 0; i < col_count; i++) {
for (var j = 0; j < row_count; j++) {
var square = '<div class="square" id = "in_col' + '_' + j + '_' + i +'"></div>';
var tile = $(square);
if (j === 0) tile.addClass('newRow');
base.append(tile);
}
}
});

GridView Freeze Header

I am using this tutorial to freeze the header of the GridView. I did everything as explained in the tutorial but I got the following error in IE9 and I don't know why.
Error:
Line: 182
Error: Unable to get value of the property 'offsetWidth': object is
null or undefined
I defined the GridView in the Javascript code as show below:
<script type = "text/javascript">
var GridId = "<%=GridView1 %>";
var ScrollHeight = 300;
window.onload = function () {
var grid = document.getElementById(GridId);
var gridWidth = grid.offsetWidth;
var gridHeight = grid.offsetHeight;
var headerCellWidths = new Array();
for (var i = 0; i < grid.getElementsByTagName("TH").length; i++) {
headerCellWidths[i] = grid.getElementsByTagName("TH")[i].offsetWidth;
}
grid.parentNode.appendChild(document.createElement("div"));
var parentDiv = grid.parentNode;
var table = document.createElement("table");
for (i = 0; i < grid.attributes.length; i++) {
if (grid.attributes[i].specified && grid.attributes[i].name != "id") {
table.setAttribute(grid.attributes[i].name, grid.attributes[i].value);
}
}
table.style.cssText = grid.style.cssText;
table.style.width = gridWidth + "px";
table.appendChild(document.createElement("tbody"));
table.getElementsByTagName("tbody")[0].appendChild(grid.getElementsByTagName("TR")[0]);
var cells = table.getElementsByTagName("TH");
var gridRow = grid.getElementsByTagName("TR")[0];
for (var i = 0; i < cells.length; i++) {
var width;
if (headerCellWidths[i] > gridRow.getElementsByTagName("TD")[i].offsetWidth) {
width = headerCellWidths[i];
}
else {
width = gridRow.getElementsByTagName("TD")[i].offsetWidth;
}
cells[i].style.width = parseInt(width - 3) + "px";
gridRow.getElementsByTagName("TD")[i].style.width = parseInt(width - 3) + "px";
}
parentDiv.removeChild(grid);
var dummyHeader = document.createElement("div");
dummyHeader.appendChild(table);
parentDiv.appendChild(dummyHeader);
var scrollableDiv = document.createElement("div");
if(parseInt(gridHeight) > ScrollHeight){
gridWidth = parseInt(gridWidth) + 17;
}
scrollableDiv.style.cssText = "overflow:auto;height:" + ScrollHeight + "px;width:" + gridWidth + "px";
scrollableDiv.appendChild(grid);
parentDiv.appendChild(scrollableDiv);
}
</script>
So how I fix this problem?
You have written code incorrectly
Instead of
var GridId = "<%=GridView1 %>";
Change to
var GridId = "<%=GridView1.ClientID %>"; //<= Check this
When ASP.Net controls are rendered their Id gets mangled and to get the mangled on client side the notation is as shown above.
Hope this solves your problem.

Categories

Resources