Andrew
Andrew

Reputation: 3560

How does one get the width of an absolute/fixed element with jquery/js, on resize?

Lets say you have a fixed or absolute positioned element:

<div>
   My fixed div.
</div>

With the following css:

div:first-of-type {
    background-color: red;
    position: fixed;
    top: 20px;
    left: 20px;
    right: 20px;
    bottom: 20px;
}

You can figure out the width via:

$(function() {
    $(window).resize(function() {
        var $myFixedDiv = $('div:first');

        console.log($myFixedDiv.width()); //$myFixedDiv.innerWidth(), $myFixedDiv.outerWidth() 
    });

});

However, when you resize the window, the width reported by both firefox and chrome is 0.

How would one figure out what the true width is?

Upvotes: 1

Views: 1567

Answers (1)

Cubic Digital Team
Cubic Digital Team

Reputation: 186

You could take the window's width and minus 40 from both axis.

var width = $(window).width()-40;
var height = $(window).height()-40;

Then rather than using the css top, left, bottom and right to set the width as I think will be unreliable in the long term I would set the div's width with the js

var myDiv = $('#myDiv');
myDiv.width = width;
myDiv.height = height;

Upvotes: 2

Related Questions