Corentin Branquet
Corentin Branquet

Reputation: 1576

Resizing window Jquery

When I scroll down into my website, I want my header to reduce its height. So I wrote this code :

function resizeHeader() {
    if ($(window).width() > 1200) {
        if ($('body').hasClass('scrolled')) {
            $('#masthead .top-header').css('height', '50px');
        } else {
            //Initial height
            $('#masthead .top-header').css('height', 'auto');
        }
    } else if ($(window).width() > 768 && $(window).width() < 989) {
        if ($('body').hasClass('scrolled')) {
            $('#masthead .top-header').css('height', '35px');
        } else {
            $('#masthead .top-header').css('height', 'auto');
        }
    }
}

/** Fix header scroll **/
$(window).scroll(function() {
    if ($(this).scrollTop() > 1) {
        $('body').addClass('scrolled');
        resizeHeader();
    } else {
        $('body').removeClass('scrolled');
        resizeHeader();
    }
});

So this code works, when I refresh my page at the wanted size, the script is working.

However, when i refresh and then I resize my window, then my header has not the height I set for this size

What I want is when I resize my window, the function is running and do action. it's always working when I refresh my page and not when I resize it.

Thanks for your help !

Upvotes: 1

Views: 35

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337550

You need to trigger a scroll event on load of the page so that your code runs. Try this:

$(window).scroll(function () {
    // your code here...
}).trigger('scroll'); // < trigger on load

Also note that it would be much more appropriate to put the logic of your resizeHeader() function in to a responsive CSS stylesheet using media queries, something like this:

#masthead .top-header {
    height: auto;
}

@media (max-width: 1200px) {
  .scrolled #masthead .top-header {
    height: 50px;
  }
}

@media (max-width: 989px) {
  .scrolled #masthead .top-header {
    height: 35px;
  }
}
var scrollTimer;
$(window).scroll(function() {
    clearTimeout(scrollTimer);
    scrollTimer = setTimeout(function() {
        $('body').toggleClass('scrolled', $(this).scrollTop() > 1);
    }, 250);
}).trigger('scroll');

Upvotes: 2

Related Questions