Infinite Scroll with JSON + Javascript data

Asked

Viewed 1,919 times

0

Personal talk... I’m developing an application where I get the data via JSON and template them via javascript, so far so good...

I need a help to create an Infinite scroll in javascript, showing 10 result and when arriving at the bottom of the page it loads 10 more, until the data is finished.

What would be the best way to do this?

Below follows my code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Xtart</title>
	<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function(){
			var url="http://xt.art.br/br.art.xt.xtart/API/";
			$("#news").html("");
			$.getJSON(url,function(data){
				$.each(data.members, function(i,user){
					var tblRow =
						"<div class='posts' style='background-image: url("+user.guid+");'>"
						+"<input type='hidden' value='"+user.ID+"'/>"
                        +"<div class='post_title'><div>"+user.post_title+"</div></div>"
						+"</div>";
					$(tblRow).appendTo("#news");
				});
			});
		});
	</script>
	<style type="text/css">
		#news{ float: left; width: 100%;}
		.posts{float: left; width: 100%; height: 200px; margin-bottom: 10px; background-position: center; background-size: cover;}
		.post_title{margin-top:120px; height: 80px; background-image:url(bg_post_title.png); background-repeat: repeat;}
		.post_title div{color: #FFFFFF !important; padding: 2px; text-transform: uppercase; text-shadow: 1px 1px #444}
	</style>
</head>

<body>
	<div id="news"></div>
</body>
</html>

2 answers

1

I managed to solve my problem with the help of @Lucasmarques.

Below I let my code work, in case someone has the same problem I had.

Thanks!

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>Xtart</title>
  <script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
      "use strict";
      var url = "http://xt.art.br/br.art.xt.xtart/API/";
      $("#news").html("");
      var mostrados = 5;
      $.getJSON(url, function(data) {
        $.each(data.members, function(i, user) {
          var tblRow = "<div class='posts' style='background-image: url(" + user.guid + "?zoom=2&resize=640%2C360);'>" + "<input type='hidden' value='" + user.ID + "'/>" + "<div class='post_title'><div>" + user.post_title + "</div></div>" + "</div>";
          $(tblRow).hide().appendTo("#news");
        }).done(function {
          var filhos = $('#news').children('.posts');
          for (var i = 0; i < mostrados; i++) {
            filhos[i].className = "posts show";
          }
          $(window).scroll(function() {
            if ($(this).scrollTop() + $(this).height() === $(document).height()) {
              var mostradosAntes = mostrados;
              mostrados += 5;
              var filhos = $('#news').children('.posts');
              for (var i = mostradosAntes; i < mostrados; i++) {
                filhos[i].className = "posts show";
              }
            }
          });
        });
      });
    });
  </script>
  <style type="text/css">
    #news {
      float: left;
      width: 100%;
    }
    
    .posts {
      float: left;
      width: 100%;
      height: 200px;
      margin-bottom: 10px;
      background-position: center;
      background-size: cover;
    }
    
    .post_title {
      margin-top: 120px;
      height: 80px;
      background-image: url(bg_post_title.png);
      background-repeat: repeat;
    }
    
    .post_title div {
      color: #FFFFFF !important;
      padding: 2px;
      text-transform: uppercase;
      text-shadow: 1px 1px #444
    }
    
    .show {
      display: block;
    }
    
    .hide {
      display: none;
    }
  </style>
</head>

<body>
  <div id="news"></div>
</body>

</html>

1


Normally this technique is used when you do not have all elements already loaded and so it is gradually loading to decrease the initial load time, but in your case you already have all the data loaded, if you still want to use it can do something like this:

/* Executar depois que os elementos da página estiverem carregados, ou seja, seu código anterior já deve ter populado o '#news'. */
var mostrados = 10; //valor inicial
var filhos = $('#news').children();
for (var i=0; i<filhos.length; i++) {
    if (i < mostrados) filhos[i].show();
    else filhos[i].hide();
}

$(window).scroll(function() { //evento de scroll na janela
    if($(window).scrollTop() == $(document).height() - $(window).height()) { //atingido o final da página
        mostrados += 10;
        var filhos = $('#news').children();
        for (var i=0; i<mostrados; i++)
            filhos[i].show();
    }
}

Note: You can remove the first loop if in your previous code add style:"display:none" in all your Ivs that are inserted to the #news except the first 10.

  • Thanks @Lucasmarques helped me a lot!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.