Pieter Dijkstra
Pieter Dijkstra

Reputation: 121

Scroll handler bug

I've an bug in my scroll.window jquery script. the function of the script is, when you as visitor scrolls to the bottom the script shows 10 more items, but there is an default. First default is 0 to 10, when you scroll it change to 10 to 20 and after that 20 to 30 etc. etc.

But what the script is doing now is, when i scroll down i get 10 to 20 and when i scroll again i get 20 to 30 and 10 to 20. and what i only need is 20 to 30.

function getEvents(first = 0, second = 10) {

var win = $(window);

$.ajax({
    dataType: 'json',
    url: '#',
    success : function(data)

    {
        console.log(first,second);
        $.each(data.slice(first,second), function(i, item) {

            content += '{html}';
            $(content).appendTo("#block-a-events");

        })
    }
});

// add counter 
var counter = 1;
// Each time the user scrolls
win.scroll(function() {
  // End of the document reached?
  if ($(document).height() - win.height() == win.scrollTop()) {
    $('#loading').show();

    getEvents(counter * 10 , ++counter * 10 );

  }
});

}

enter image description here

Upvotes: 0

Views: 40

Answers (1)

Oliver
Oliver

Reputation: 4091

I don't think you're closing the getEvents() function correctly. Add another } before var counter = 1; and bring var win = $(window); after the getEvents function:

function getEvents(first = 0, second = 10) {
  // ajax call
  console.log(first);
  console.log(second);
}

var win = $(window);
// add counter 
var counter = 1;
// Each time the user scrolls
win.scroll(function() {
  // End of the document reached?
  if ($(document).height() - win.height() == win.scrollTop()) {
    getEvents(counter * 10 , (counter + 1) * 10 );
    counter += 2;
  }
});
html {
  height: 800px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Scroll up and down

Full code:

function getEvents(first = 0, second = 10) {

$.ajax({
    dataType: 'json',
    url: '#',
    success : function(data)

    {
        console.log(first,second);
        $.each(data.slice(first,second), function(i, item) {

            content += '{html}';
            $(content).appendTo("#block-a-events");

        })
    }
});
}

var win = $(window);
// add counter 
var counter = 1;
// Each time the user scrolls
win.scroll(function() {
  // End of the document reached?
  if ($(document).height() - win.height() == win.scrollTop()) {
    $('#loading').show();
    getEvents(counter * 10 , (counter + 1) * 10 );
    counter += 2;
  }
});

Upvotes: 1

Related Questions