user3745886
user3745886

Reputation: 21

Getting scrollTop() to perform only once

I want scrollTop to trigger only once, so that the red box doesn't appear again after it has been closed with the button.

I know there is .one(), but I have no idea how to apply it to my code. Below is my code and jsfiddle.

<div id="box-pop">This is a red box.
    <button class="box-close">Close</button>
</div>


$(document).scroll(function () {
    if ($(this).scrollTop() > 100) {
        $('#box-pop').fadeIn(500);
    }
});
$(document).ready(function () {
    $(".box-close").click(function () {
        $("#box-pop").fadeOut(200)
    });

});

http://jsfiddle.net/3LG6t/3/

Upvotes: 2

Views: 1144

Answers (4)

LGVentura
LGVentura

Reputation: 1547

For a better performance in your page, what about this?

$("#box-pop").fadeOut(200,function(){
    $(this).remove();
});

Demo: http://jsfiddle.net/3LG6t/5/

And take a look at this topics:

  1. Differences between detach(), hide() and remove() - jQuery
  2. jQuery detach() v/s remove() v/s hide()
  3. Why remove() or detach() instead of hide()?

Upvotes: 3

Attenzione
Attenzione

Reputation: 842

if you are using scroll for other functionallity, you need to create separate function, otherwise see @Gavin42 example

fadeInBox = function () {
    if ($(window).scrollTop() > 100) {
        $('#box-pop').fadeIn(500);
    }
}

$(document).on('scroll', fadeInBox);
$(document).ready(function () {
    $(".box-close").click(function () {
        $(document).off('scroll', fadeInBox);
        $("#box-pop").fadeOut(200);
    });
});

Upvotes: 0

Kris Erickson
Kris Erickson

Reputation: 33834

One is used the same way bind or on is. Scroll itself really isn't an actual function but a shortcut to on that performs the following:

.on('scroll', function () {

}

However you need to get something to work once after a condition, so you would use off after using on.

<div id="box-pop">This is a red box.
    <button class="box-close">Close</button>
</div>


$(document).on('scroll', function fadeBoxIn() {
    if ($(this).scrollTop() > 100) {
        $('#box-pop').fadeIn(500);
        $(document).off('scroll', fadeBoxIn);

    }
});
$(document).ready(function () {
    $(".box-close").click(function () {
        $("#box-pop").fadeOut(200)
    });

});

See the fiddle.

Upvotes: 2

Gavin42
Gavin42

Reputation: 490

Try $( "document").unbind( "scroll" ); :

$(document).scroll(function () {
  if ($(this).scrollTop() > 100) {
    $('#box-pop').fadeIn(500);
  }
});
$(document).ready(function () {
  $(".box-close").click(function () {
    $("#box-pop").fadeOut(200)
    $(document).unbind("scroll");        
  });
});

or conditionally rebind the scroll function within the $(".box-close").click().

Upvotes: 0

Related Questions