agon024
agon024

Reputation: 1007

jQuery width(); not working properly

I think I'm going crazy :).

In my js file I have:

alert( $('.element').width() );

it will alert "867"...Which is wrong.

In the Chrome or Firefox console i type:

$('.element').width();

It responds with 567. Which is correct.

Am I missing something here. Should I be doing this a different way. Cause the code in the js file is messing everyting up.

BTW the element does have a width and float set through CSS -- width: 80% and float: left. But the browser consoles still give me the right width.

Thanks.

Upvotes: 4

Views: 8833

Answers (4)

Abel Callejo
Abel Callejo

Reputation: 14959

Cause

The .width() method is subject to the browser's reflow and repaint. The browser reflows and repaints the DOM objects during runtime. Visual changes to the HTML document also trigger reflow and repaint.

With these reasons, the .width() method will return a zero (0) value during browser states where reflow-and-repaint is still about to happen.

Solution

Always call the .width() method after reflow-and-repaint.

Common cases

Case #1. Document ready VS Window load

$(document).ready(function(){
    // during this state, .width() is more likely equal to zero (0)
});

During the $(document).ready, DOM objects are ready to be manipulated. However, the browser is still doing reflow-and-repaint. Thus, there is a huge chance you will get .width() = 0

$(window).load(function(){
    // during this state, .width() is more likely to have the right values
});

At $(window).load, DOM objects are ready to be manipulated and the browser is done with reflow and have repainted everything on the document.

Case #2. Hidden VS Shown

HTML

<div style="display:none">
    <button>Foo</button>
</div>

jQuery

// still hidden
$('button').width(); // 0

// now shown
$('div').show();
$('button').width(); // right value

Again, to fix the zero width issue, always call the .width() method after reflow-and-repaint.

Upvotes: 0

Erik Grosskurth
Erik Grosskurth

Reputation: 3932

Try this:

$(window).load(function(){
    alert( $('.element').width() );
});

Upvotes: 3

RPichioli
RPichioli

Reputation: 3345

Sometimes you have to work with properties thinking about padding and margin extra sizes. Commands like innerWidth take care about the padding of the element, but outerWidth corresponds to the size counting it's border (and if receive true their margin too).

Take a look at this topic already closed, i hope this must help you: What is difference between width, innerWidth and outerWidth, height, innerHeight and outerHeight in jQuery

Upvotes: 0

Raf
Raf

Reputation: 352

try

$('.element').outerWidth();

Let me know if it helps

Upvotes: 0

Related Questions