DisgruntledGoat
DisgruntledGoat

Reputation: 72510

Determining how big an element will be in Javascript

I need to position an element in the exact centre of the page (using fixed positioning) and need to calculate the expected size. For example I would add HTML like this:

<div class="window" style="left: X; top: Y">
    <h3 class="title">Title</h3>
    <img src="file.jpg" width="300" height="200" />
    <div class="controls">Some stuff</div>
</div>

The width will be the image width plus some padding. I want to determine what the height of the element will be by getting the styles from the stylesheet, then calculate the correct position, then write the HTML with the right styles.

Upvotes: 2

Views: 221

Answers (5)

Luca Matteis
Luca Matteis

Reputation: 29267

Have you tried this pure CSS way of centering an image in a box?

Upvotes: 0

nickf
nickf

Reputation: 546025

You can only tell once it's been added to the document (that is, you can't tell the expected size and you won't be able to do it server-side).

So, in Javascript, set the visibility to hidden, add it to the document, check its outerHeight or with jQuery call $('.window').height(), reposition as needed, and then change visibility back to visible.

...or, use this plugin:

jQuery(function($) {
    $.fn.vCenter = function(options) {
        var empty = {},
            defaults = {
                allowNegative : false,
                relativeToBody : true
            },
            settings = $.extend(empty, defaults, options)
        ;

        var isVisible = this.is(":visible");
        if (!isVisible) {
            this.css({visibility : "hidden"}).show();
        }
        if (settings.relativeToBody && this.offsetParent().get(0).nodeName.toLowerCase() != "body") {
            this.appendTo(document.body);
        }
        var pos = {
            sTop : function() {
                return window.pageYOffset || $.boxModel && document.documentElement.scrollTop || document.body.scrollTop;
            },
            wHeight : function() {
                if ($.browser.opera || ($.browser.safari && parseInt($.browser.version, 10) > 520)) {
                    return window.innerHeight - (($(document).height() > window.innerHeight) ? getScrollbarWidth() : 0);
                } else if ($.browser.safari) {
                    return window.innerHeight;
                } else {
                    return $.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
                }
            }
        };
        return this.each(function(index) {
            if (index === 0) {
                var $this = $(this),
                    $w = $(window),
                    topPos = ($w.height() - $this.height()) / 2 + $w.scrollTop()
                ;
                if (topPos < 0 && !settings.allowNegative) topPos = 0;

                $this.css({
                    position: 'absolute',
                    marginTop: '0',
                    top: topPos //pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2)
                });
                if (!isVisible) {
                    $this.css({visibility : ""}).hide();
                }
            }
        });
    };
    $.fn.hCenter = function(options) {
        var empty = {},
            defaults = {
                allowNegative : false,
                relativeToBody : true
            },
            settings = $.extend(empty, defaults, options)
        ;

        if (settings.relativeToBody && this.offsetParent().get(0).nodeName.toLowerCase() != "body") {
            this.appendTo(document.body);
        }
        return this.each(function(index) {
            if (index === 0) {
                var $this = $(this),
                    $d = $(document),
                    leftPos = ($d.width() - $this.width()) / 2 + $d.scrollLeft()
                ;
                if (leftPos < 0 && !settings.allowNegative) leftPos = 0;
                $this.css({
                    position: "absolute",
                    left: leftPos
                });
            }
        });
    };
    $.fn.hvCenter = function(options) {
        return this.vCenter(options).hCenter(options);
    };
});

Usage:

$('.window').hvCenter();  // horizontal and vertical center

Upvotes: 2

Mike
Mike

Reputation: 5036

With jQuery, you want to use the outerHeight and outerWidth functions.

Without jQuery, you want to use offsetHeight and offsetWidth DOM properties.

Note that these both include the padding and border in their calculations, whereas jQuery height and width do not. Optionally, outerHeight and outerWidth can be made to include margin, but offsetHeight and offsetWidth cannot.

Upvotes: 2

dmitrig01
dmitrig01

Reputation: 769

You can use CSS:

.window {
  margin: 0 auto;
}

Upvotes: -1

David Hellsing
David Hellsing

Reputation: 108500

you can get width and height using width() and height()

so $('.window').height() will return the computed height of the element in your case.

Upvotes: 0

Related Questions