Phate
Phate

Reputation: 6622

jquery `.width()` returns negative values when on elements inside of an accordion

This is the fiddle http://jsfiddle.net/j08691/sG92g/

And my code is pretty simple:

var html = "";

 html += "<div><button class='mybutton'>shortbutton</button></div>";
 html += "<div><button class='mybutton'>short</button></div>";
 html += "<div><button class='mybutton'>loooooooooooooooooooooooooong</button></div>";

 $("#mymenu").html(html);
 $("#myaccordion").accordion({
             heightStyle: "content",
             collapsible: true,
             active: false 
         });


   $( ".mybutton" ).button().click(function( event ) {
                event.preventDefault();
 });

var greatestWidth = 0;   // Stores the greatest width
$(".mybutton").each(function() {   
var theWidth = $(this).width();   // Grab the current width
console.log(" widht: "+theWidth);
if( theWidth > greatestWidth) {   
   greatestWidth = theWidth;     //    set greatestWidth to theWidth
 }
});
         
$(".mybutton").width(greatestWidth); 

I have a list of buttons inside of an accordion, I'd like to set each button of the same size, anyway if the accordion is open and the elements are visible, everything works great. If, like in this example, the accordion is closed, this function returns a negative number or zero thus failing.

Upvotes: 1

Views: 3992

Answers (1)

paulitto
paulitto

Reputation: 4673

Try using outerWidth instead of width it will take into account paddings and borders.

var theWidth = $(this).outerWidth();

In all the rest, you code should be ok.

see example


Update:

When the elements are invisible, jquery's .width() will always give zero.

To workaround this you can e.g. clone element, temporarily set it to display:block and visibility:hidden (or zero opacity), measure its width and then remove. Something like this:

$(".mybutton").each(function() {

         // create temp element to grab width of an invisible element
         var tmpbtn = $(this).clone().appendTo( "body" ).css({'display':'block', 'visibility': 'hidden'});
         var theWidth = tmpbtn.width();
         tmpbtn.remove();

         console.log(theWidth); //this is for checking
         if( theWidth > greatestWidth) {   // If theWidth > the greatestWidth so far,
             greatestWidth = theWidth;     //    set greatestWidth to theWidth
         }
     });

see updated fiddle

Upvotes: 8

Related Questions