0

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!

1
  • 2
    Event handlers are usually supposed to be added once; you are adding a new scroll handler each time the button is clicked. Commented Jan 9, 2019 at 14:12

1 Answer 1

1

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');
        }
    });

}
Sign up to request clarification or add additional context in comments.

1 Comment

Works great, thanks! If I wanted to add a time delay to the addClass, do you know how I can do that? Just so the class 'active' doesn't appear immediately on scroll

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.