YSbakker
YSbakker

Reputation: 707

Setting margin-top of one element to the height of another element using JQuery

I'm trying to have a header at the top with a non-fixed height but a fixed position, and below that a content area. Now, I simply added a fixed padding-top to the element so the content would show below the header. I'm trying to do this using JavaScript and JQuery. I think the way I did it would be the best way, but it doesn't quite work.

[HTML]

<div class="contentPage" id="page_1" name="templates">
    <div class="contentPageHeader">
        <a href="#menu">
            <div class="pageBack">
                <h4>Back</h4>
            </div>
        </a>

        <h3>Templates</h3>
    </div>
    <div class="contentPageContent">
    </div>
</div>

[JS]

var headerHeight = $('.contentPageHeader').css( 'height' );
$('contentPageHeader').css('margin-top', headerHeight);

For a full demo visit this JSfiddle

Upvotes: 1

Views: 4869

Answers (3)

Shrinivas Pai
Shrinivas Pai

Reputation: 7711

Try this

$(document).ready(function () {
    $("a").click(function () {

        if (this.hash) {
            var hash = this.hash.substr(1);

            var $toElement = $("div[name=" + hash + "]");

            if (hash == "menu") {
                $('.contentPage').fadeOut(300);
                $($toElement).fadeIn(300);

            } else {
                $('#menu_holder').fadeOut(300);
                $($toElement).fadeIn(300);

            }
        }
       var headerHeight = $('.contentPageHeader').css( 'height' );  //your code added here
       $('.contentPageHeader').css('margin-top', headerHeight);  
    });


});

Fiddle:https://jsfiddle.net/mdeujc0u/3/

Updated fiddle: https://jsfiddle.net/mdeujc0u/5/

Upvotes: 0

Andrey
Andrey

Reputation: 1553

You should to fix your javascript:

    var headerHeight = $('.contentPageHeader').outerHeight();
    $('.contentPageContent').css('margin-top', headerHeight);

Also this code should be placed inside the click method.

jsfiddle

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

You need to define the unit for marginTop for eg. px or %:

$('.contentPageHeader').css('margin-top', headerHeight + 'px');
//^^ missed a selector (the dot)

Upvotes: 0

Related Questions