Richy
Richy

Reputation: 117

$(window).scrollTop(); does not fired quick enough

I been trying to make a header that will shrink by amount that you have scrolled and then stop and a certain point. There is also a logo that will move up within this

The only problem is $(window).scrollTop(); does not fire quick enough. so if you scroll too fast the logo will be outside the header or the header might be pixels too big.

i cant think of a better way to do this.. any help or ideas would be appreciated

here is my code

var widgets = {
    header: function() {
        var $header = $('.header');
        var $logo = $('.header__title');
        var $headerHeight = $header.height();
        $(window).on('scroll resize', function(event) {
            var windowWidth = window.innerWidth;
            var windowScrollTop = $(window).scrollTop();


            if( windowScrollTop < 100) {
                $logo.css('margin-top','-'+(windowScrollTop)+'px'); 
            }

            if ( windowScrollTop < 230) {   
                $header.css('height',($headerHeight - windowScrollTop)+'px');
            }
        });
    }
}

$(document).ready(function() {
    widgets.header();
    .....

example is here http://jsfiddle.net/7wp51gu6/

Upvotes: 2

Views: 396

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

You can set the final state on else of the two conditions

if (windowScrollTop < 100) {
    $logo.css('margin-top', '-' + (windowScrollTop) + 'px');
} else {
     $logo.css('margin-top', '-100px');
}

if (windowScrollTop < 230) {
    $header.css('height', ($headerHeight - windowScrollTop) + 'px');
} else {
    $header.css('height', ($headerHeight - 230) + 'px');
}

Demo at http://jsfiddle.net/gaby/7wp51gu6/7/

Upvotes: 2

Cayce K
Cayce K

Reputation: 2338

I made some quick changes and need some quick feedback from you, but check this fiddle out...

http://jsfiddle.net/7wp51gu6/6/

I updated the script here only:

if (windowScrollTop >= 100) {
    $logo.css('margin-top', '-100px');
}else{
    $logo.css('margin-top',0);
}

It basically sets it to the top where you want it when it is greater than or equal to 100. Also sets it back when you are at the top which is where you want it.

Also made a change to some css that pushes your primary content down 312px. Check that out as well. That isn't 100% necessary just assuming based on your current display something you will need in the future.

Upvotes: 1

Related Questions