databot
databot

Reputation: 131

Calculate height with JQuery for sticky header

I want to change the first header to be 100% page height and then using the javascript use this height to have the sticky header appear after the first header.

So I need to calculate the height of the page I think using jquery. Not sure how to implement it.

http://jsfiddle.net/obmerk99/VvKq3/1/

#header{
    width: 100%; background-color: red;
    border: 1px solid black;height:40px;}
#header_stick{
    width: 100%; background-color: black;
    border: 1px dotted grey;color:white;}
.stick{
    position:fixed;top:0;opacity:0.7;}
h1{
    font-size: 130%; padding-bottom:1px;}



 jQuery(window).scroll(function(){
    var top = jQuery(window).scrollTop();
if(top>42) // height of float header
jQuery('#header_stick').addClass('stick');
else
 jQuery('#header_stick').removeClass('stick');
    })



<div id="header">My floating header</div>
<div id="header_stick">My stick header</div>

Upvotes: 1

Views: 3651

Answers (1)

Todd
Todd

Reputation: 5454

I was able to adapt your code into the following: Here's a fiddle

$(function() {
    var wH = $(window).height(),
        top;
    $("#header").css("height", wH);
    $(window).scroll(function(){
        top = jQuery(window).scrollTop();
        if(top>wH) // height of float header
            $('#header_stick').addClass('stick');
        else
          $('#header_stick').removeClass('stick');
     });
});

and for shiggles, watch me play this fiddle.

$(function() {
    // cache vars
    var wH = $(window).height(),
        $stick = $("#header_stick"),
        isStick;

    // adjust 1st div height
    $("#header").css("height", wH);

    // sexier implementation with toggle
    $(window).scroll(function(){
        $stick.toggleClass('stick', jQuery(window).scrollTop() > wH);
     });
});

Upvotes: 3

Related Questions