chronotrigga
chronotrigga

Reputation: 609

Removing and adding class via .js

I'm working on a header banner that is hidden at the start but appears when the user scrolls down on the page. When the user scrolls back up to the top of the page it should disappear again and keep doing it until the user exits (there is an exit button on the banner which adds a cookie so if the user exits it won't show again).

enter image description here

The issue I'm having is that either the banner won't show up again when I scroll back up to the top of the page, or it will just keep showing up even after exiting. I've tried several options but nothing has worked so far.

function desktopHeader() {
  $(window).on('scroll', function() {
    console.log( $(this).scrollTop() );
  });

  var $headerBanner = $('.module-header-banner');

  $('.close-btn').on("click", function () {
    $.cookie("headerbanner", "exit", {expires: 2/24});
    $('.module-header-banner').addClass("exit").fadeOut();
  });

  if($.cookie('headerbanner') == null) {
    if($(window).scrollTop() > $('.site-header').height()){
      $headerBanner.addClass('active').fadeIn();
    } 

    $(window).scroll(function() {
      if($(window).scrollTop() > $('.site-header').height()){
        $headerBanner.addClass('active');
      } else if($(window).scrollTop() < $('.site-header').height()) {
        $headerBanner.removeClass('active');
      }
    });
  }
}

At a loss -- if anyone has any advice would be best appreciated. Thanks!

Upvotes: 0

Views: 64

Answers (1)

programtreasures
programtreasures

Reputation: 4298

Try to add your scroll event outside of the click function, here is a updated code

function desktopHeader() {
$(window).on('scroll', function() {
    console.log( $(this).scrollTop() );
});

var $headerBanner = $('.module-header-banner');

$('.close-btn').on("click", function () {

    $.cookie("headerbanner", "exit", {expires: 2/24});

    $('.module-header-banner').addClass("exit").fadeOut();
    });

    if($.cookie('headerbanner') == null) {

    if($(window).scrollTop() > $('.site-header').height()){
            $headerBanner.addClass('active').fadeIn();
    } 

}


    $(window).scroll(function() {
        if($(window).scrollTop() > $('.site-header').height()){
                $headerBanner.addClass('active');
        }   

        else if($(window).scrollTop() < $('.site-header').height()) {
            $headerBanner.removeClass('active');
        }
    });

}

Upvotes: 1

Related Questions