Making divs fill up a containing div? - javascript

I've been searching the site for an answer, and nothing I've come across seems to help. I'm trying to make it so that a default (and eventually user-specified) number of divs fill up the containing div like a grid. I'm trying to figure out how to make the size of the boxes I append to the parent change depending on how many are added, while always filling up the div, if that makes sense. So for instance, if I specify 9, I should have 3 rows and 3 columns. If I specify 62, then I'm looking for 16 rows and 16 columns, always filling up (or coming close to, anyway) the containing div. Here's a JSfiddle I have so far: https://jsfiddle.net/psyonix/1g9p59bx/1/ Here's the code as it is:
var d = ("<div class='square'></div>");
function createGrid(numSquares){
for(var i = 0; i < numSquares; i++){
$('#g_area').append(d);
}
var squareSize = Math.floor(580/numSquares );
$('.square').height(squareSize);
$('.square').width(squareSize);
};
$(document).ready(function(){
createGrid(64);
});

The only issue you had was setting the square size to 1/64th of the height instead of 1/(64^.5) of the height. Essentially you where just making one row. https://jsfiddle.net/1g9p59bx/7/
var d = ("<div class='square'></div>");
function createGrid(numSquares){
var gridContainer = $('#g_area');
for(var i = 0; i < numSquares; i++){
gridContainer.append(d);
}
var squareSize = Math.floor(580/(Math.sqrt(numSquares)) );
$('.square').height(squareSize);
$('.square').width(squareSize);
};
$(document).ready(function(){
createGrid(64);
});

I would create a little jqueryplugin for that. You can call it in every container you like: containerForGrid.createGrid(cols, rows)
(function($){
$.fn.createGrid = function(cols, rows) {
// get width and height of sorrounding container
var w = this.width()
var h = this.height()
// calculate width and height of one cell
var colWidth = w / cols
var rowHeight = h / rows
// loop over all rows
for(var i = rows; --i;){
// loop over all cols
for(var j = cols; --j;){
$('<div>').css({
width:colWidth,
height:rowHeight,
float:'left'
}).appendTo(this)
}
}
}
})(jQuery)
jQuery('div').createGrid(10,10)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:1000px;height:500px">
</div>

Related

Reduce size of cells on Monthview

I am trying to get a full month of events view on one computer page (Full HD) to avoid scrolling left to right.
if (view.type == 'resourceTimelineMonth')
{
setTimeout(function (){
var cols = document.getElementsByTagName ("col");
for (var i = 0; i < cols.length; i++) {
cols[i].style="width:2px";
}
},30);
}
After the calendar is loaded I am resizing the columns of the table to 2px.
It works as expected for higher columns size than 29-30 pixels.
Less than that does not result to what should be.
How to circumvent this limit ? Any idea ?
Thanks
Here is a workaround for those interested. Instead of trying to reduce the columns themselves I scaled down the calendar itself. You can change the scaling manually or better doing a ratio with the innerWidth of the screen.
if (view.type == 'resourceTimelineMonth') {
setTimeout(function () {
var box =
document.getElementsByClassName('fc-view-container');
var box1 =
document.getElementsByClassName('fc-scroller-canvas');
var box2 =
document.getElementsByClassName('fc-time-area fc-widget-header');
var box3 = document.getElementsByClassName('fc-cell-text');
box1[3].setAttribute('style','width:auto;');
box[0].setAttribute('style','transform:scale(0.25,1);transform-origin:0
center;width:6600px');
box2[0].setAttribute('style',';transform-origin:0 center');
for (let i=0; i< box3.length;i++) {
box3[i].setAttribute('style','font-size:10px;transform:scale(3,1)');}
},30);
}
Sorry for the poor formatting, cannot seem to make the identation work...

Can I divide a text box by paragraph in Google Slides using Apps Script?

I am trying to design some code in Apps Script that can be put on any Google Slides presentation and split every text box by paragraphs so every paragraph has its own text box.
I started out using var shape = slide.insertShape(SlidesApp.ShapeType.TEXT_BOX, 50, 50, 300, 300); to make the new text boxes like google describes to use in most of its tutorials but it 'couldn't identify the TEXT_BOX type' so I found .insertTextBox and that seems to work better but I've found other problems.
I can use .getParagraphs to find the number of paragraphs in a text box but I can't tell if it doesn't include the contents of each paragraph or if I'm just not using the correct command to get the text from the paragraph. I have also tried to find an alternative to find the beginning of each paragraph and divide the text from there but I can't find a command for that either. Maybe would I have to use .indexOf to find each /n or /r, or is there a simpler way?
I'm also having a problem where my equations to divide up the text box size are giving me undefined answers and I've tried declaring the variables as numbers but it just makes things worse.
function myFunction() { // get slides in the presentation and establish 'for' variables
var slide = SlidesApp.getActivePresentation().getSlides();
var i;
var j;
var k;
for (i = 0; i < slide.length; i++) { // get the text boxes on each slide
var text = slide[i].getShapes();
for (j = 0; j < text.length; j++) { // get the location of and the paragraphs in each textbox (locations don't work)
var top = text[j].getTop;
var left = text[j].getLeft;
var width = text[j].getWidth;
var height = text[j].getHeight;
var paragraph = text[j].getText().getParagraphs();
for (k = 0; k < paragraph.length; k++){ // make a textbox for each paragraph distributed vertically over the original textbox
var content = text[j].getRange(paragraph[k]); //I was hoping this would fill with the contents of current paragraph
var shapeheight = height / paragraph.length; //NaN and I don't know why
var shapetop = height * k + top; //also doesn't work these should all be numbers
slide[i].insertTextBox(content, left, shapetop, width, shapeheight);
}
text[j].remove(); //delete original textbox on slide
}
}
}
Here are pictures of what I'm trying to do:
Slide before intended changes
Approximate slide after intended changes
I believe your goal as follows.
You want to split each paragraph in a text box as each text box on Google Slides.
You want to achieve this using Google Apps Script.
Modification points:
In your script,
getTop, getLeft, getWidth and getHeight are the method. So please add ().
About var content = text[j].getRange(paragraph[k]), getRange has no arguments.
About var shapeheight = height / paragraph.length, in this case, this can be put outof the for loop.
About var shapetop = height * k + top, in this case, that might be var shapetop = shapeheight * k + top.
When above points are reflected to your script, it becomes as follows.
Modified script:
function myFunction() {
var slide = SlidesApp.getActivePresentation().getSlides();
var i;
var j;
var k;
for (i = 0; i < slide.length; i++) {
var text = slide[i].getShapes();
for (j = 0; j < text.length; j++) {
var top = text[j].getTop(); // Modified
var left = text[j].getLeft(); // Modified
var width = text[j].getWidth(); // Modified
var height = text[j].getHeight(); // Modified
var paragraph = text[j].getText().getParagraphs();
var shapeheight = height / paragraph.length; // Modified
for (k = 0; k < paragraph.length; k++) {
var content = paragraph[k].getRange().asString(); // Modified
var shapetop = shapeheight * k + top; // Modified
slide[i].insertTextBox(content, left, shapetop, width, shapeheight);
}
text[j].remove();
}
}
}
Note:
In the current stage, it seems that AutoFit cannot be set. By this, when slide[i].insertTextBox(content, left, shapetop, width, shapeheight) is used, the text deviates a little from the box. So in this case, how about not using shapeheight? In this case, please modify slide[i].insertTextBox(content, left, shapetop, width, shapeheight); as follows.
var t = slide[i].insertTextBox(content);
t.setLeft(left);
t.setTop(shapetop);
t.setWidth(width);
References:
getTop()
getLeft()
getWidth()
getHeight()
getRange()
insertTextBox(text)

Adding 7x7 grid based tabla-data tags to table via Javascript (Battleships game)

I am trying to create a simple battleship game with Javascript. The game should feature a 7x7 grid system and the battleships should be placed randomly on the grid, both vertically and horizontally.
Here's the code creating the 1x7 grid (horizontally):
/* Declare length of battleground */
var battleground = 7;
/* Calculate and position the battleships */
while (battleground < 7);
var battlegroundCalc = parseInt(battleground) - 2;
var randomLoc = Math.floor(Math.random() * battlegroundCalc);
var location1 = randomLoc;
var location2 = location1 + 1;
var location3 = location2 + 1;
console.log(location1);
console.log(location2);
console.log(location3);
/* Add tiles to construct the battleground */
for (var i = 0; i < battleground; i++){
document.getElementById('tableRow').innerHTML +="<td id='"+i+"'></td>"
};
However I am having difficulties in figuring out how to create multiple rows, so I get a 7x7 grid.
If anybody could help me out with that, I would be really grateful.
Thanks in advance.
Here's a way:
var dimensionx = 7;
var grid = new Array(dimensionx);
var i, j, row, box;
// this is our table
var board = document.getElementById('tbody_id');
for (i = 0; i < grid.length; i++) {
grid[i] = new Array(dimensionx);
grid[i].fill('~'); //fill the grid with water
row = document.createElement('tr');
for (j = 0; j < grid[i].length; j++) {
box = document.createElement('td');
box.setAttribute('id', "" + i + j); //practical identification for cells
row.appendChild(box);
}
board.appendChild(row);
}
The difference here is that I create a 2-dimensional array before I start using it (all I do is clear the cells before the whole thing is constructed). After that, just reference the cell you want by grid[i][j] and the table cell by its id, in the same way the attribute is set.
Here's a fiddle. It also has an update_board() function for convenience.
I would have answered sooner but I got carried away and almost implemented the entire game in jsFiddle, until I stopped myself.

Tips to improve performance of Javascript

I have a requirement where I need to set the height of each row of a table based on the corresponding row in another table.The table has around 500 rows.
I have written the below Javascript, but the performance is really bad around 8000 ms.
How can I make this faster, appreciate any tips .
var start = new Date().getTime();
var rows = document.getElementById("table1").rows;
var dup_rows = document.getElementById("table2").rows;
var num_rows = rows.length;
var num_dup = dup_rows.length;
for (var i = 0; i < num_rows; ++i) {
var hg = rows[i].offsetHeight;
rows[i].style.height = hg +'px';
dup_rows[i].style.height = hg +'px';
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
Based on the Suggestion to edit the tables outside of DOM, I tried the below, but the outerHeight / offsetHeight returns 0 when the table is removed from DOM.
clone_small = $('#table2').clone();
clone_main_tab = $('#table1').clone();
$("#table2").remove();
$("#table1").remove();
$(clone_main_tab).find("tr").each(function(i) {
var hg = 0;
hg = $(this).offsetHeight; // If I hard code the height it works
// alert(hg);
$(this).height(hg);
clone_small.find("tr").eq(i).height(hg);
});
How can I set the height of these rows outside the DOM ?
Remove the element that you are modifying from the DOM, then re-insert them when you are done modifying them. This prevents the browser having to reflow the document with every change, only doing it once when you're all finished.
Isn't dup_rows[i].style.height = rows[i].style.height better?
I was finally able to achieve some improvement in performance by using the below code
$clone_table1 = $('#table1').clone();
$clone_table2 = $('#table2').clone();
$('#table2').remove();
$trow2 = $('#table1').find('tr');
$trow = $clone_table1.find('tr');
$trow3 = $clone_table2.find('tr');
$trow.each(function(i) {
var hg = 0;
hg = $trow2.eq(i).outerHeight();
$(this).height(hg);
$trow3.eq(i).height(hg);
});
$parent2.append($clone_table2);
$('#table1').remove();
$parent1.append($clone_table1);

How to create array and divs with a unique height using jQuery?

I need 100 small divs for my chart, every time I generate them, I they all appear as the same height; the last value from the array.
var valuesG = new Array(100);
for (i = 0; i < valuesG.length; i++ ) {
valuesG[i] = Math.floor(Math.random() * 101);
$("#second").append("<div class='single'></div>");
$(".single").css('height', valuesG[i])
}
Any ideas why this is happening?
You are applying the new height to ALL the .single elements in every iteration. In the last iteration, they end up having the same height.
You could do it like this:
$('<div class="single">')
.css('height', valuesG[i])
.appendTo($('#second'));
Also, your code is not very efficient, take a look at this:
var valuesG = [], //array literal
$elements = $(); //empty jQuery object
for (var i = 0; i < 100; i++) { //we don't have to query array length each iteration
valuesG[i] = Math.floor(Math.random()*101);
//collect the elements into a jQuery object
$elements = $elements.add($('<div class="single">').css('height', valuesG[i]));
}
$elements.appendTo($("#second")); //insert to DOM once - much quicker
jsFiddle Demo
Currently, you're selecting all elements with class single. To get the desired effect, use the appendTo method in the way as shown below.
Side note, the generated heights are not unique, but random. It's possible that two elements exist with, say, height 50. See this question for a method to generate unique random numbers.
var valuesG = new Array(100), i;
for ( i=0; i < valuesG.length; i++ )
{
valuesG[i] = Math.floor(Math.random()*101);
$("<div class='single'></div>")
.css( 'height', valuesG[i] )
.appendTo("#second");
}
You get only one height(last one) because you set same css class in all div and update it's height in every loop so last height value will be applied to all.
As a solution try this:
for ( i=0; i < valuesG.length; i++ ) {
valuesG[i] = Math.floor(Math.random()*101);
$("<div class='single'></div>").css('height',valuesG[i]).appendTo("#second");
}

Categories