Nick Maddren
Nick Maddren

Reputation: 583

$(window).width() if statement running when it shouldn't

Hey guys I am having an issue with $(window).width if statements in jQuery. For some reason my function is running even when the window width is smaller than 991 pixels however my if statement states that it should run if the window width is greater than 991.

function ctaFixTop() {
  var mn = $("#new-car-offer-cta");
  var offerHead = $('#new-car-offer-head');
  mns = "new-car-offer-cta-active";
  var hdr = 0;
  var ctaHeight = $("#new-car-offer-cta").height();
  $('.header-wrapper, #top-bar, #new-car-back, #new-car-offer-head').each(function() {
      hdr += $(this).outerHeight();
  });
  if ($(window).width() > 991) {
    $(window).scroll(function() {
        if ($(this).scrollTop() > hdr) {
            offerHead.css('margin-bottom', ctaHeight);
            mn.addClass(mns);
        } else {
            offerHead.css('margin-bottom', 0);
            mn.removeClass(mns);
        }
    });
  }
}
$(window).resize(ctaFixTop);
ctaFixTop();

As you can see the ctaFixTop function is being called twice, once on initial load and whenever the window is resized. When I initially load the page with a window width below 991px the function works how it should however if I then increase the windows size past 911px and size it back down under 911px the $(window).scroll function will be called even when it's wrapped in the if statement that states that it should only run if the window width is greater than 991.

Any idea why this might be happening as I have tried trouble shooting this and simply can't understand why the function is being called even with the if statement around it.

Thanks

Upvotes: 0

Views: 387

Answers (1)

phreakv6
phreakv6

Reputation: 2165

That is because the scroll event is already attached to the window and you are not removing it. What you need to do is put the

  if ($(window).width() > 991) {

inside the .scroll() method like this.

 $(window).scroll(function() {
  if ($(window).width() > 991) {
    if ($(this).scrollTop() > hdr) {
        offerHead.css('margin-bottom', ctaHeight);
        mn.addClass(mns);
    } else {
        offerHead.css('margin-bottom', 0);
        mn.removeClass(mns);
    }
}});

Upvotes: 3

Related Questions