JQuery width () returns invalid values ​​in table cells

In the plugin that I am writing, I have terrible problems with the width of the table cells. All I do is get the width of the table cell using the jQuery .width() function, and then set the same cell as the returned width. Mainly:

 $table.find('> thead > tr > th').each( function() { var $th = $(this); $th.css({width: $th.width()}); } ); 

However, in many cases, the returned width is incorrect and changing it changes the width of the cells. At first it seemed to me that it was disabled at 1px, so I added 1px to the returned width. But with tighter borders, it's bigger, but it doesn't seem to be just adding border widths. For starters, there are obviously two borders, but only with a width of 1 border. And with different border widths it seems almost random what value you need to add.

Here is an example with my code - part of the width setting starts 1 second after the page loads, so you can see the change. Is there a reliable way to get / set table cell widths in Javascript?

+6
source share
1 answer

demo: http://so.devilmaycode.it/jquery-width-returning-incorrect-values-on-table-cells/

this is your plugin almost rewritten ... tested on IE7-10, Chrome, Firefox

  (function($) { $.fn.stickyHeader = function() { return this.each(function() { // apply to tables only if (this.tagName.toUpperCase() !== 'TABLE') return; var $table = $(this).addClass('jq-stickyHeader-table'); var $wrapper = $table.wrap('<div/>').parent().addClass('jq-stickyHeader-wrapper'); // set each TH to its own width $table.find('thead th').each(function() { $(this).html('<div>' + $(this).text() + '</div>'); $(this).width($(this).find('div').width()); }); $wrapper.width($table.width()).height($table.height()); // clone entire table and remove tbody (performance seems fine) var $stickyheader = $table.find('thead').clone().wrap('<table/>').parent().addClass('jq-stickyHeader'); // hack for IE7 if ($.browser.msie && parseInt($.browser.version, 10) == 7) { $table.find('tr:first-child td').css('border-top', 0); } $stickyheader.css({ 'width' : $table.width(), }).insertAfter($table); $(window).scroll(function() { // while over the table, show sticky header var currTop = ($(this).scrollTop() - $table.offset().top); $stickyheader.stop(true, true).animate({ top : currTop }, 100); var scrollLimit = $table.offset().top + ($table.height() - $stickyheader.height()); var isVisible = (currTop > $table.offset().top && currTop < scrollLimit) ? 'block' : 'none'; $stickyheader.css({ display : isVisible }); }); }); }; })(jQuery); $(function() { $('table').stickyHeader(); }); 

css inside the demo source!

+1
source

All Articles