<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@2.0.3" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script data-require="underscore.js@*" data-semver="1.5.2" src="//cdn.jsdelivr.net/underscorejs/1.5.2/underscore-min.js"></script>
    <script data-require="select2@*" data-semver="3.4.5" src="//cdn.jsdelivr.net/select2/3.4.5/select2.min.js"></script>
    <link data-require="select2@*" data-semver="3.4.5" rel="stylesheet" href="//cdn.jsdelivr.net/select2/3.4.5/select2.css" />
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <h1>client-side infinite scrolling</h1>
    <h2>with <a href="http://ivaynberg.github.io/select2">select2</a></h2>
    <input type="text" id="infinite" style="width: 200px"/>
    <script src="script.js"></script>
  </body>

</html>
/*

Shows how to achieve infinite paging in select2, using a local data 
source, rather than Ajaxing on the fly.

Found a starting point in select2 issues, written by
https://github.com/ivorbosloper

Then I fixed some things, and removed the underscore dependency.
https://github.com/bruno-c

*/

$(function() {

  "use strict";
  
// Seems fast enough to me even with OVER 9000 items.

  var HOW_MANY = 9002;
  
  var testdata = [];
  for (var i = 0; i < HOW_MANY; i++){
    testdata.push({
        id: i,
        text: "Item #" + i
    })
  }
  
// Important: Make sure to return true when your filter
// receives an empty string as a search term.

  function contains(str1, str2) {
    return new RegExp(str2, "i").test(str1);
  }
  
  $("#infinite").select2({
    data: testdata,
    query: function(q) {
      var pageSize = 50,
          results = this.data.filter(function(e) {
            return contains(e.text, q.term);
          });
          
// Get a page sized slice of data from the results of filtering the data set.
      
      var paged = results.slice((q.page - 1) * pageSize, q.page * pageSize);
      
      q.callback({
        results: paged,
        more: results.length >= q.page * pageSize
      });
    }
  });

})