Ryan.Patrick
Ryan.Patrick

Reputation: 25

$(window).scroll event firing inconsistently

Making a header that resizes after scrolling, what I have works when I scroll downwards, then fails when I scroll all the way to the top and attempt to get the header to get larger again. Sometimes it'll resize, and sometimes it won't; and it's never instant.

Here's the Code:

$(window).scroll(function () {
if ($(document).scrollTop() >= 50) {
    $('.header').animate({
        'padding': 0
    }, 300);
} else {
    $('.header').animate({
        'padding-top': 15,
        'padding-right': 7,
        'padding-bottom': 15,
        'padding-left': 25
    }, 300);
}});

Thanks in advance

Upvotes: 0

Views: 94

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

You need to have a flag for this, which checks whether the same thing has been done or not. There might be glitches in the following code, but need to tweak it in the right environment. If needed, change the first line to true.

var flag = false;
$(window).scroll(function () {
  if ($(document).scrollTop() >= 50) {
    if (flag) {
      $('.header').animate({
        'padding': 0
      }, 300);
      flag = false;
    }
  } else {
    if (!flag) {
      $('.header').animate({
        'padding-top': 15,
        'padding-right': 7,
        'padding-bottom': 15,
        'padding-left': 25
      }, 300);
      flag = true;
    }
  }
});

Setting this flag here, will make sure that the function gets executed only once, during its range.

Upvotes: 1

Related Questions