I'm having some weird issue with widths of table cells. All I try to do, is to get the width of the table cell using .width() function, then set that width on the same cell in width attribute:
$table.find('tr:first td').each(function () {
var actualWidth = $(this).width();
$(this).attr("width", actualWidth);
});
Every time I do that, it gets a different width for some cells (Usually reduces one and increase another).
I saw a similar question from 2012: jQuery width() returning incorrect values on table cells
But it's quite old and the accepted answer doesn't seem to work.
fiddle: https://jsfiddle.net/awolf/40pj1b2u/
Any help will be appreciated.
I think there are two problems in one. All related to the table-cell display.
The use of border attribute (border="1") in the
<table> probably messes up the width value when read. Probably the same when setting attr('width') value. In order to match the closest real value, you can use innerWidth() as #Adam P suggested.
Table cells width depends on the full available table width. In your jsfiddle sample, when expanding the table zone, cells' width are increasing. So, from each cell Width, you can compute the global table width, and apply it.
See this https://jsfiddle.net/piiantom/72dvm0v4/, taken from yours, with JS adjustments.
Table border can be changed, the JS still works
I would consider this a bug.
My interpretation:
When reading the width, it gets the content-width.
When setting it, the box gets rendered and then the border set (taking 1px from content each time).
Same with .attr(), .prop(), and .width().
Have a look at box-sizing, .innerWidth() and .outerWidth()!
Related
I have a wide table – possibly very wide – and I want the table to be as wide as necessary to fit everything, i.e. as-if it the width was auto (and the screen was wider).
But, by default, tables seem to never exceed the size of their containers!
I've found an answer using JavaScript, but is there a pure CSS answer too? Or a better JavaScript solution?
Here's a JSFiddle fiddle with an example table. Note that in this example the content is bigger than the 'screen', but the desired effect should cause the width of the cells to be large enough so that the text of each cell is all on a single line.
Per GChabot's answer, I don't want the cells to be bigger than their contents. Per their subsequent comment, by "fit everything", I'm of course referring to the Goldilocks fit, i.e. just enough so that contents don't wrap, but no larger.
Set the cells up so they do not wrap
td { white-space: nowrap; }
Depending on what you mean by "fit everything", you might want to define a min-width for your tds:
min-width:250px;
That way, each cell has a reasonable size to display some text, on one or more lines (or just one if you set them as nowrap as epascarello suggested). If you are displaying fixed-size element (such as images), the table should expand by default.
CSS overflow should fix your issue take a look at this post http://css-tricks.com/the-css-overflow-property/
Here's the quick-and-dirty JavaScript I'm using now:
$('#table-container').attr('style', 'width: 1000%');
$('#table-container').attr('style', 'width: ' + $('#tblMain').width() + 'px;');
#table-container refers to a div surrounding the table; the table has an id of tblMain.
I know this won't work if the table is 10 times wider than the current screen size, but a general solution should be pretty easy to implement.
I'm currently working on eliminating jQuery from some code that I've written, and I've got a portion of code in which I was computing both the inner and outer widths of some span elements. It seems like .getBoundingClientRect() works fine for getting the outer width of an element, but I'm a bit stuck on getting the inner width. (i.e. the width of the element sans padding and borders.)
I'm using d3 to create my spans, and I need to compute their inner widths so that I can effectively set the widths of some other elements in order to get them to line up. Is there a good way of getting inner width for a div without manually checking and subtracting the various .css properties that could affect it?
Not sure how stable this is, but the method that seems to be working is using window.getComputedStyle(element).width.
This gives the computed style as "95px", where 95 is the inner width (in pixels). I'm using parseInt(window.getComputedStyle(element).width) to get the inner width of the element as a number.
Taken from jQuery:
Math.max(element.scrollWidth, element.offsetWidth, element.clientWidth)
You could try .offsetWidth. Here's a fiddle.
i have integrated backgrid.js in my current assignment everything is working fine but i would like to know that how to set height and width for a cell in the backgrid table?
Is it possible to change the width and height of the backgrid table also how to use on mouse over events on the cell?
You can use jquery and CSS for changing cell height and cell width. You should also be able to use the css classes for cells to detect hovers as well.
Take a look at http://backgridjs.com/misc/styling.html. It explains all the classNames used for the different cell types.
Sorry I can't offer you any examples. I'd need a better explanation of your problem for that.
Yes, you can use CSS. You are using Backgrid so you have table with class 'backgrid'. Override existing Backgrid CSS. For example:
table.backgrid td {
//do something
}
Same as above, you can override height and width of backgrid table.
I am trying to implement a table structure in which the header remains fixed when i scroll down. I have used 2 tables for this purpose. The first table has the header values and the second table have the corresponding data(length of data in each column might vary as the data is populated dynamically). The problem is that the header width and data column width are not matching exactly.
I have written some code like shown below to dynamically alter the column width
$('#tdCheckAllBody').width($('#tdCheckAllHead').width());
$('#tdLoginBody').width($('#tdLoginHead').width());
$('#tdStatusBody').width($('#tdStatusHead').width());
$('#tdFNameBody').width($('#tdFNameHead').width());
$('#tdLNameBody').width($('#tdLNameHead').width());
$('#tdCompBody').width($('#tdCompHead').width());
But it doesnt seem to work properly. Any help appreciated.
Use this method
$(window).scroll(function(){
$("#id of the table header").offset({top:$("#id of the control which u placed the scrolling").scrollTop()});
});
Created a working fiddle for this:
http://jsfiddle.net/terjeto/dx7H5/
Offcourse if your case is different, you might need to tweak a litle. In my opinion the problematic areas are if the table use dynamic or % width and coping with the "auto" scrollbar which takes up approx 18px, and offcourse if the table needs horizontal scrollbars it complicates things a litle needing the onscroll event.
Could it be that your exmple is not accurate because of lacking reset-css code?
I use this: http://developer.yahoo.com/yui/reset/
I have table with multiple rows, showing items for sale. When the user clicks on a row, a Javascript inserts / shows a new row right beneath it with details about the item. The issue is when the description is long, it forces the column widths to readjust / resize. This shifts the columns positions and is really annoying, especially for the user. Right now, I have my table.style.tableLayout: auto. I actually prefer it this way, because the columns are adjusted to the content.
My question is: how do I dynamically "lock" the widths of the columns in my table so that when I insert / show the new row, the columns do not readjust / resize?
I've tried:
dynamically setting the table to temporarily "tableLayout: fixed"
inserting / showing my new row
changing the table back to "tableLayout: auto"
Actions 1 & 2 works in in FireFox, but not in Safari and IE (6 & 7). However, doing all three seems to prevent the columns from shifting too much.
The frustration is unbearable ... loosing lots of sleep ... please help!
Thanks.
For those looking for the code (this is done in jQuery). This also assumes the first row has the proper widths for each cell. Pretty easy changes if needed.
$('table.class_of_table_to_fix tr:first td').each(function() {
$(this).css({'width': $(this).width()+"px"});
});
I would set a percent width on each column simply as a guide. Set it just once on the TH of each column. The browser will still adjust the columns to content if necessary, but the columns will stay in place more consistently.
Next, I would never put css "white-space:nowrap" anywhere on that table. A long description should not break the table layout, it should wrap around properly on multiple lines, and be readable if you set the widths on each column to suit the type of data. Similarly I would keep the use of (non breakable spaces) to dates, times and numbers and allow the text to wrap.
Other than that, I do this at my job on a dialy basis, and there's a time when you need to stop ulling hairs asking the browser to do something it's not designed to do. Content should flow and adapt. Locking column widths to pixels is 99.99999% of the time a bad idea.
PS: If you really, reeally, REALLY need to lock columns, the only solution I'm aware of that works with CSS2 and accross all browsers is to use images. You could insert a 1px high transparent gif image in each column, and counting in the padding of the cells (TD), set a pixel width on each image (IMG), instead of on the columns (TH/TD). You could hide those in the TH for example. You can leave the images at 1 pixel wide and set percent widths on TDs, and when you open a new row, you would get each column width minus TD Padding, and set that to the corresponding IMG. I haven't tried! I just know that in many projects I've worked on, I've used small gif images to lock a minimum vertical spacing between columns, for example.
I had a similar problem when I was implementing a table with groups that could be toggled. I wanted the initial ratio between the columns to stay the same without fixing the widths of the columns. By default the browser would change the widths depending on the visibility of the table's rows, which was undesirable.
I went ahead and followed #faB's suggestion of applying percentages, but doing so using a small script that would calculate the percentages of the th elements and apply them after the initial render. This made my columns stay the same width, even with all rows hidden.
Here's the script, which uses jQuery:
(function($){
var lock_widths = function() {
var total_width = $('table').innerWidth();
var headers = $('table th');
var leftover = 100;
$.each(headers, function(ix, el) {
var header = $(el), width;
// on the last call use the leftover percentage
if (ix == headers.length - 1) {
width = leftover;
} else {
leftover -= width = header.outerWidth() / total_width * 100;
}
header.css({'width': width + '%'});
});
};
$(document).ready(lock_widths);
})(jQuery);
Tested in IE7+, Firefox and Chrome. This works for my special case because I have header columns as a reference, but it could be rewritten to measure some other columns.
You can display the details of the row beneath the clicked one in DIV and set its
style="overflow:auto";
so that details will wrap and scrollbar will be available to display entire text.
I don´t know if you´re familiar with jquery, but that´s what I would use - in combination with a separate class for the column that´s causing resizing in the new row - to:
Calculate / get the with of the column
Set the with of the afore mentioned class
Add the row
I haven´t tried it, but that should do it.
By the way, there are probably other ways to do it, I´m just more familiar with jquery (for point 1. and 2.).