imp
imp

Reputation: 470

Ignore Function?

So I've got an div that slides down when you scroll near the bottom of the page. In that div, I have an "X" anchor that slides it up again (this is in jQuery). But if I scroll, the div slides down again (naturally). So I want the X to first of all, make "#topDiv" slide up, and then ignore the function that makes it slideDown.

Full code:

  $("#topDiv").hide();

  $(window).scroll(function () {
      if ($(window).scrollTop() + $(window).height() > $(document).height() - 500) {
          $("#topDiv").slideDown();
      }


      if ($(window).scrollTop() + $(window).height() < $(document).height() - 800) {

          $("#topDiv").slideUp();
      }
      $("#closeTop").click(function () {
          $("#topDiv").slideUp();
          return false;
      });
  });

Demo Page ( http://tutorials.underbakke.net/js/function/ )

Upvotes: 1

Views: 1642

Answers (2)

adeneo
adeneo

Reputation: 318312

You could use the on/off methods to unbind the slidedown after the "X" is clicked

$("#topDiv").hide();

$(window).on('scroll', showTopDiv);

function showTopDiv() {
      if ($(window).scrollTop() + $(window).height() > $(document).height() - 500) {
          $("#topDiv").slideDown();
      }
}

$(window).on('scroll', function() {
      if ($(window).scrollTop() + $(window).height() < $(document).height() - 800) {
          $("#topDiv").slideUp();
      }
});

$("#closeTop").click(function () {
      $("#topDiv").slideUp();
      $(window).off('scroll', showTopDiv);
      return false;
});

Also, in your slideup function, adding $("#topDiv").is(':visible') to the if statement will make sure it is'nt executed uneccessary.

And is there really a need to bind the click function on every scroll?

Upvotes: 3

Jesse Pollak
Jesse Pollak

Reputation: 1600

Try this:

$("#topDiv").hide();

$(window).addEventListener('scroll', function(event) {
   if ($(window).scrollTop() + $(window).height() > $(document).height() - 500) {
      $("#topDiv").slideDown();
  }


  if ($(window).scrollTop() + $(window).height() < $(document).height() - 800) {
      $("#topDiv").slideUp();
  }

  $("#closeTop").click(function () {
      $("#topDiv").slideUp();
      $(window).removeEventListener('scroll',arguments.callee,false);
  });
}

Upvotes: -1

Related Questions