Cannot get the width of an absolute position element with jquery

1.8k views Asked by At

Please help me, i cannot get the width of an absolute position element with jquery. My element uses: height: 100% and width: auto via CSS.

I use $(element).width() but obtain a 0. Here is an example: http://codepen.io/anon/pen/LVjBvz

I need the element take the width of the inside image. This image has 4000x800px but i use width:100% and height:auto in css to have the image in fullscreen

1

There are 1 answers

1
j08691 On BEST ANSWER

Your code is executing before the image has a change to fully load. Use the $(window).load( to wait for it to complete:

$(window).load(function () {
    var contimg;
    contimg = $('#cont_img');
    ancho = contimg.width();
    alert(ancho);
})

jsFiddle example

Ref: https://api.jquery.com/load-event/ and https://learn.jquery.com/using-jquery-core/document-ready/

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.