Aligning columns from different tables - javascript

Let's say I have two tables with some text in between:
<table>
<tr><td>A</td><td>0000</td><td>Some text goes here...</td></tr>
<tr><td>B</td><td>11</td><td>... and here</td></tr>
</table>
Some text goes here.
<table>
<tr><td>CCC</td><td>1</td><td>Some text goes here...</td></tr>
<tr><td>DDD</td><td>0</td><td>... and here</td></tr>
</table>
Is is possible to make these two tables having the same column width?
That is I want the first column of table 1 to be 3 characters (e.g. CCC) big ; and I want the second column of table 2 to be 4 characters (e.g. 0000) big.
Please note that I don't know what the width of each column should be, therefor I don't want to define it beforehand in a CSS file.
I'm more interested in a dynamic approach using Javascript.
The different steps would be something like :
Build the two tables;
Get the maximum width of columns 1 and 2;
Update the CSS properties of my tables using these values.

(put ids on your table)
You can use jQuery selectors to get all your width values of your tds like :
var maxWidth = 0;
$("#table1 td").each(function() {
var width = $(this).css("width");
if(width > maxWidth) maxWidth = width;
});
And then
$("#table1 td").css("width", width);

Using JQuery you could do the following:
$(document).ready(function() {
var tdWidth = 0;
$('td').each(function() {
width = $(this).width();
if(width > tdWidth) tdWidth = width;
});
$('td').css("width", tdWidth);
});

Related

Get next table cell vertically in table with rowspans

I need to find index of cell in table below a given cell. Imagine that I don't know anything about td_end, I just click at td_start and need to find td_end. Example (need find index of red cell(td_end), knowing index of green cell (td_start)): http://jsfiddle.net/r5BDW/65/
Problem that table will contain a lot of cells with rowspan attr, so usual searching by equal index will not work. Any advice how to find such cells?
example table:
<table border="1" style="width: 100%;">
<tr><td>111</td><td rowspan="3">22</td><td>3</td></tr>
<tr><td>111</td><td>3</td></tr>
<tr><td>111</td><td class="td_start">3</td></tr>
<tr><td>111</td><td>22</td><td class="td_end">3</td></tr>
<tr><td>111</td><td>22</td><td>3</td></tr>
<tr><td>111</td><td >22</td><td>3</td></tr>
</table>
console.log($('.td_start').index() ) // =1
console.log($('.td_end').index() ) // =2
I think that would be almost a crazy act to guess all the possible colspan and rowspan combinations.
What I would try with, is to literally
"touch" the element that is visually beneath the selector element using elementFromPoint
jsFiddle demo
$.fn.nextVert = function(){
var b = this[0].getBoundingClientRect();
var nxtV = document.elementFromPoint(b.left, b.bottom+10);
if(nxtV.tagName==="TD") return $(nxtV);
};
$('.td_start').nextVert().text("hello");
console.log( $('.td_start').nextVert().index() ); // 2
by simply getting the elementFromPoint
starting from the this bottom value + some tiny offset (I used 10px)
chek this solution: http://jsfiddle.net/r5BDW/68/
find td with same left position
jQuery
$(document).ready(function() {
var $td2=$('.td_start2');
fidnBelow($td2);
var $td=$('.td_start');
fidnBelow($td);
});
function fidnBelow($td)
{
var rez='';
var p=$td.position();
var left=p.left;
var td_count=$('tr').size();
var ind_tr=$td.parent().index();
var $table=$('#table');
ind_tr++;
for(i=ind_tr;i<td_count;i++)
{
var $below_tr=$table.find('tr').eq(i)
$below_tr.find('td').each(function(){
var tp=$(this).position();
var tleft=tp.left;
if(left==tp.left) rez=$(this).html();
})
if(rez!='') break;
}
alert(rez);
}

How to find width of inner elements

I couldn't find any other questions asking the same thing, though that may be a problem with my search phrasing.
I'm trying to figure out how to find the largest width of all elements contained inside of a container div with a fixed width. So, in the image below, the black box is the container div with a fixed width. The red box represents the contents of the container div, which are subject to change. I want to find the width of the red box, using only the black box in js.
Here is a jsfiddle with what I've been working on/trying:
http://jsfiddle.net/w87k5/1/
the current jquery functions I've tried, with no success:
.width();
.innerWidth();
.outerWidth();
.scrollLeft();
Note: I do not know ANYTHING about the contents of this container. They could be any html element or mix of html elements, from divs to imgs to iframes. I could put a "red box" without a fixed width surrounding them. Overflow of the black box will be hidden.
Update: There could be any number of children in the container. Like this: http://jsfiddle.net/w87k5/3/
Update 2: I'm going to run benchmark speed tests on all of the answers to see which one is the fastest, and select one after that. Thanks for all your input!
Benchmarks:
I generated 1000 divs with a random width of inbetween 0 and 100, recorded the Date().getTime(), did the test, then recorded time again. Here are the results:
~2418 avg. milliseconds with the for loop for length. I might have messed this one up somehow?
for (var i = 1; i <= count; i++){
var q = $("#box :nth-child(" + i + ")").width();
if(q > box){
box = q;
}
}
~34.4 avg. ms for the .each loop.
~22.4 avg. ms for the .map function. (Chosen answer.)
If you need all nested elements can search with * selector which will return all descendent elements:
var widthArray=$('#box *').map(function(){
return $(this).outerWidth();
}).get();
var maxWIdth= Math.max.apply(Math, widthArray);
For just children:
var widthArray=$('#box').children().map(function(){....
You could use .each() to cycle though each child element.
jsFiddle example
var widths = [];
$('#box').children().each(function(i){
widths[i] = $(this).width();
});
alert(Math.max.apply(Math, widths));
Which will return the width of the child element with the largest width.
Get the number of children, and loop through to get the width of each
$(document).ready(function () {
var count = $("#box").children().length;
var h = 0;
for (var i = 1; i <= count; i++) {
max = $("#box :nth-child(" + i + ")").width();
var h = Math.max(max, h);
}
alert(h);
});
http://jsfiddle.net/JDVN3/1/
Please not that the index starts from 1 and not 0.
Check out: http://api.jquery.com/nth-child-selector/

Dynamic Table Width

I have a table cell in which other tables are displayed (with background colors). The inner tables aren't always shown; they can be hidden via a button (change class with jQuery). Now I want the outer cell to always be filled with color. That means if only one table is displayed, its width should be 100%. When two are displayed, each width should be 50%, and so on.
How am I supposed to solve this?
Here's an example:
...
<td>
<table class="show"><tr><td></td></tr></table>
<table class=""><tr><td></td></tr></table>
<table class="show"><tr><td></td></tr></table>
</td>
...
In this case, the width should be 50%
You can change the width value with Jquery.
var count_table = $(".show").length; // count ".show" elements
$(".show").each(function{ // iteration on each ".show"
var width = 100/count_table; // % value of new width
$(this).css("width", width+"%"); // CSS modification
});
This code is just adapted for one TD element. You need to iterate on each "td" too.
(I hope I answered your problem)
To change the width of your elements you can use jquery.
Here's the page explaining how.
Here is another way: http://jsfiddle.net/ypJDz/1
A bit too complicated for what you need, but a great deal of possibility to expand.
function resizeTables() {
var baby = $("td > table.show"),
amount = baby.length,
mother = $("body");
baby.width(function () {
var w = mother.width() / amount;
return w;
});
}
resizeTables();
$("button").click(function () {
var $this = $(this),
ID = $this.index() + 1;
$("td > table:nth-child(" + ID + ")").toggleClass("show");
resizeTables();
});

Lock table cell width, without specifying it

I'm trying to dynamically create a table from js, although I do know the exact width and height of the table, I do not know the actual width of table cell. I know that it is possible to find the width of the each cell, but I was wondering if you can actually lock it without specifying the width of the cell.
Link to jsfiddle:
http://jsfiddle.net/j3TEz/21/
My js file:
window.addEventListener('load',init,false);
function init(){
var table = document.getElementById('myTable');
var tr = 3;
var td=5;
var innerTable = '';
for(var trCounter=0;trCounter<tr;trCounter++){
innerTable+='<tr>';
for(var tdCounter=0;tdCounter<td;tdCounter++){
var id=(trCounter*td)+tdCounter;
innerTable+='<td id="'+id+'" onclick="addText('+id+')"></td>';
}
innerTable+='</tr>';
}
table.style.width="600px";
table.style.height="300px";
table.style.border="1px solid black";
table.innerHTML=innerTable;
}
function addText(id){
document.getElementById(id).innerHTML="Lorem Ipsum";
}
Css table-layout set to fixed will keep the columns width fixed, the size will be determined by the first row columns.
Hope this help.

Dynamic width of Table as per column

I have one table which display data as from Dynamic Content, I want to make table width 100% when there is 6 cols. and table width auto if less the 5 cols.
I tried with CSS but, when there is only two cols, it expand two cols to full width while have table 100% width and looks awkward.
Is there any Javascript, jQuery script available to get this result?
Using jQuery and ensuring you choose the first row in the table body in case the thead has a different layout.
function setTableWidth(tableId) {
var $tbl = $('#'+tableId);
var newWidth = $tbl.find('tbody>tr:eq(0)>td').length > 5 ? '100%' : 'auto';
$tbl.width(newWidth)
}
Depending on how you're loading the dynamic content, there might be an easier way, but this function should do what you need:
function setTableWidth(tableId) {
myTable = document.getElementById('tableId');
if (myTable.getElementsByTagName('tr')[0].getElementsByTagName('td').length > 5)
myTable.style.width = '100%';
else
myTable.style.width = 'auto';
}
Note though, that it won't work if any of the cells in the first row have a colspan. It's simply counting the number of columns in the first row and setting the width based on that.

Categories