Jürgen Paul
Jürgen Paul

Reputation: 15007

jQuery rebind $(window).scroll() after a successful ajax call

I have made this infinitely scrolling script, but I can't rebind the window scroll after I unbinded it. Here's the script:

$(function(){
    $(window).scroll(function(){
        var mostOfTheWayDown = ($(document).height() - $(window).height()) * 2 / 3;
        if ($(window).scrollTop() >= mostOfTheWayDown) {
            $(window).unbind('scroll');
            $.ajax({
                url: 'loadmore',
                data: {lastrank: lastrank},
                dataType: 'json',
                type: 'POST',
                success: function(json){
                    //some work here
                    $(window).bind('scroll');
                }
            });
        }
    });
});​

How can I rebind the window scroll after a successful ajax call?

Upvotes: 1

Views: 7223

Answers (3)

AlexKempton
AlexKempton

Reputation: 1698

Similar way to other answers, but with binding instead.

$(function(){

  function scrollStuff() {

    var mostOfTheWayDown = ($(document).height() - $(window).height()) * 2 / 3;
    if ($(window).scrollTop() >= mostOfTheWayDown)
    {
      $(window).unbind('scroll');
      $.ajax({
        url: 'loadmore',
        data: {lastrank: lastrank},
        dataType: 'json',
        type: 'POST',
        success: function(json){
          //some work here
          $(window).bind('scroll', scrollStuff);
        }
      });
    }
  }

  $(window).bind('scroll', scrollStuff);
});

Upvotes: -1

noob
noob

Reputation: 9202

$(function(){
    var scrollFunction = function(){
        var mostOfTheWayDown = ($(document).height() - $(window).height()) * 2 / 3;
        if ($(window).scrollTop() >= mostOfTheWayDown) {
            $(window).unbind("scroll");
            $.ajax({
                url: "loadmore",
                data: {lastrank: lastrank},
                dataType: "json",
                type: "POST",
                success: function(json){
                    //some work here

                    $(window).scroll(scrollFunction);
                }
            });
        }
    };
    $(window).scroll(scrollFunction);
});​

Upvotes: 7

Anthony Grist
Anthony Grist

Reputation: 38345

You need to pass a callback function to the .bind() method that does whatever it is you want to happen when the scroll event fires. You'll also want to call unbind('scroll') first, so you don't end up with two functions being executed every time the user scrolls.

Upvotes: 0

Related Questions