javascriptjqueryhtmlcssjquery-ui

jQuery UI .position() misses height of target element set with jQuery .height()


This is my HTML:

<div class="full-height">
    <h1>Lorem</h1>
</div>

I'm setting the height of div.full-height with jQuery as follows:

$(document).ready(function() {
    function setHeight() {
        viewportHeight = $(window).height();
        $('.full-height').height(viewportHeight);
    };
    setHeight();

    $(window).resize(function() {
        setHeight();
    });
});

Now I try to set the position of the h1 in div.full-height to center center with jQuery UI as follows:

$('.full-height > h1').position({
    my: 'center center',
    at: 'center center',
    of: '.full-height'
});

The problem is, that it's only positioned correctly if I set a fixed height property in CSS.

Otherwise div.full-height has full height, but the h2 inside it sticks at the top because jQuery UI's .position() function doesn't know that div.full-height has 100% height.

How can I get it working?


Solution

  • I just solved the problem by including the jQuery UI function inside if the resizing function as follows:

    $(document).ready(function() {
        function setHeight() {
            viewportHeight = $(window).height();
            $('.full-height').height(viewportHeight);
            $('.full-height > h1').position({
                my: 'center center',
                at: 'center center',
                of: '.full-height'
            });
        };
        setHeight();
    
        $(window).resize(function() {
            setHeight();
        });
    });