user3241466 user3241466 - 5 months ago 15
jQuery Question

Stopping the scrolling animation once it has been closed

I have a newsletter section that appears on the site when the person starts to scroll down after a certain point. On this newsletter section there is a close button that allows this Newsletter section to be closed. However the problem is that when they close the newsletter and start scrolling again it reappears. So the first function is cancelling out the second. How can the close button remove the newsletter button from the page and not reappear when they start to scroll again?

var amountScrolled = 300;

$(window).scroll(function() {
if ( $(window).scrollTop() > amountScrolled ) {
$('.Newsletter_btn').fadeIn('slow');
} else {
$('.Newsletter_btn').fadeOut('slow');
}
});

$(document).ready(function(c) {
$('.alert-close').on('click', function(c){
$(this).parent().fadeOut('slow', function(c){ });
});
});


×

Answer

It's simple. Just add a variable, what listenst is the newsletter has closed?

I called it showNewsletter.

When you load the pages, it's true. When use scroll down, it appears. If user has closed, then set it to false, so now you know, you should not appear it again.

var amountScrolled = 300;
var showNewsletter = true; //init 

$(window).scroll(function () {

    if ($(window).scrollTop() > amountScrolled) {
        if (showNewsletter) { //show only if not turned off
            $('.Newsletter_btn').fadeIn('slow');
        }
    } else {
        $('.Newsletter_btn').fadeOut('slow');
    }
});

$(document).ready(function (c) {
    $('.alert-close').on('click', function (c) {
        $(this).parent().fadeOut('slow', function (c) { });
        showNewsletter = false; // turn off
    });
});
Comments