JQuery width (); not working correctly

I think I'm going crazy :).

In my js file I have:

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

he will warn "867" ... What is wrong.

In the Chrome or Firefox console, type:

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

He answers 567. What is right.

Did I miss something. Should I do it differently. The reason the code in the js file is useless.

The BTW element has a width and a float set via CSS - width: 80% and float: left. But browser consoles still give me the correct width.

Thank.

+4
source share
4 answers

Try the following:

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

try

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

Let me know if this helps.

0
source

, . , innerWidth, , outerWidth , ( ).

, , : , , , innerHeight Height jQuery

0

.width() reflow and repaint. DOM . HTML- .

.width() (0) , .

.width() reflow-and-repaint.

№1. Windows

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

$(document).ready DOM . , . , , .width()= 0

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

$(window).load DOM , .

№2. VS

HTML

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

JQuery

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

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

, , .width() reflow-and-repaint.

0
source

All Articles