JS implementation load More function instances _javascript tips

Source: Internet
Author: User
Tags mysql query

A front page of the project shows that the purchased item is required to drop the load more. on how to implement the "load more" feature, there are plug-ins available on the web, such as the more famous use of iscroll.js implementation of the pull load more, drop-down refresh function.

But the actual use is very troublesome. Because it is a third-party plug-in, to be used in accordance with the method defined by each other, it always feels very uncomfortable to use. Plus iscroll.js itself does not have the integration to load more functions, and needs to be expanded itself. To continue using the Iscroll.js implementation to load more versatile, the above links can be seen.

H5 project needs to implement a simple paging function, because it is the mobile side, consider "load more" will be better, rather than the PC side of the page.

Based on button implementation load more

The simplest is to give a load of more buttons, if there is data, click Load More, continue to pull a few data, until no more data, hide load more buttons.

The effect is as follows:

Page HTML:

<div class= "Content" >
  <div class= "Weui_panel weui_panel_access" >
    <div class= "WEUI_PANEL_HD" > Articles List </div>
    <div class= "weui_panel_bd js-blog-list" >
      
    </div>
  </div>
  
  <!--load More buttons-->
  <div class= "Js-load-more" > Load more </div>
  
</div>
<script src= " Js/zepto.min.js "></script>

Load More button styles: loadmore.css:

@charset "Utf-8";

js-load-more{
  padding:0 15px;
  width:120px;
  height:30px;
  Background-color: #D31733;
  Color: #fff;
  line-height:30px;
  Text-align:center;
  border-radius:5px;
  margin:20px Auto;
  border:0 none;
  font-size:16px;
  display:none;/* default does not show, the AJAX call success before deciding whether to show or not * *
}

To load more JS code:

$ (function () {/

  * Initialize/
  var counter = 0;/* Counter/
  var pagestart = 0;/*offset*/
  var pageSize = 4;/*size* /
  
  * * First load/*
  getData (Pagestart, pageSize);
  
  /* Listen to load more * *
  (document). On (' click ', '. Js-load-more ', function () {
    counter + +;
    Pagestart = counter * pageSize;
    
    GetData (Pagestart, pageSize);
  });


There's not much code here. where GetData (Pagestart, pageSize) is the business logic code that pulls data from the service end. Here's an example:

function GetData (offset,size) {$.ajax ({type: ' Get ', url: ' Json/blog.json ', DataType: ' JSON ', success:
      function (reponse) {var data = reponse.list;
  
      var sum = reponse.list.length;
      
      var result = ';
      
      /**** business logic BLOCK: To achieve the mosaic HTML content and append to the page *********///console.log (offset, size, sum); * * If the remaining records are not enough paging, let the number of pages to take the remaining records * For example, the page is 5, only 2, then only 2 * * * * * actual mysql query does not write this will not have a problem/if (Sum-offset
      < size) {size = Sum-offset; /* Use the For loop to simulate limit (offset,size) in SQL (var i=offset; i< (offset+size); i++) {result = ' & Lt;div class= "Weui_media_box weui_media_text" > ' + ' <a href= "' + Data[i].url + '" target= "_blank" >

It's still quite simple.

Load more with scrolling event implementation
Above we through the button click Implementation Load more, the whole process is relatively simple. Here, I provide another way to implement loading more: Based on scrolling (scroll) events.

Directly attached to the code:

$ (function () {/

  * Initialize/
  var counter = 0;/* Counter/
  var pagestart = 0;/*offset*/
  var pageSize = 7;/*size*/
   var isend = false;/* End Sign
  
  /* First load
  /* GetData (Pagestart, pageSize);
  
  /* Listen to load more 
  /$ (window). Scroll (function () {
    if (isend = = True) {return
      ;
    }

    Loads the new content
    //Core code if ($ (document) when scrolling to the bottom 100 pixel.
    height ()-$ (this). ScrollTop ()-$ (this). Height () <100) {
      counter + +;
      Pagestart = counter * pageSize;
      
      GetData (Pagestart, pageSize);}});


You can see that the code changes little, mainly look at the core code in the judgment conditions: when scrolling to the bottom of 100 pixels above, load new content.

The business logic GetData (Pagestart, pageSize) simply changes the logic in the if (offset + size) >= sum) to:

if (offset + size) >= sum) {
  isend = true;//No More
}

On the line.

Of course, this also has to optimize the place, for example: how to prevent scrolling too fast, the server did not have time to respond to cause multiple requests?

Comprehensive example

Through the example above, it is obvious that the second is better than clicking. But the second method has a problem:

If you set the page size by 2 or 3 each time (size=2), the total record is 20, and you will find that you cannot trigger a downward scrolling load for more logic. It's a good time to have a load of more click buttons.

Therefore, we can put these two methods together:

The default use of scrolling events to load more, when the display number is too small is not enough to trigger downward scrolling load more logic, use load more click event.
Here, I have a simple abstraction of loading more of this behavior, and write a simple plugin:

Loadmore.js

* * * loadmore.js * Load More * * @time 2016-4-18 17:40:25 * @author feihong ~ * @email jiancaigege@163.com * The parameters that can be passed by default are: size, Scroll can customize */;(function (w,$) {var Loadmore = {* * Single page load more common method * * @param callback callback method *

      param Config Custom parameter * */get:function (callback, config) {var config = config. config: {};/* Prevent error from not passing parameters * * var counter = 0;
      /* Counter */var Pagestart = 0; var pageSize = config.size?

      Config.size:10;
        /* Default by clicking Load More * * (document). On (' click ', '. Js-load-more ', function () {counter + +;
        
        Pagestart = counter * pageSize;
      Callback && callback (config, Pagestart, pageSize);
      
      }); /* To load more by automatic monitoring scrolling events, OPTIONAL support * * Config.isend = false; /* End sign */Config.isajax = false;
          /* Prevent scrolling too fast, the server did not have time to respond to cause multiple requests/$ (window). Scroll (function () {/* * open rolling load/if (!config.scroll) {
        Return }//* If there is no more data in the rolling load, when the request is occurring, you cannotContinue with */if (Config.isend = = True | | config.isajax = = true) {return; */* When scrolling to the bottom 100 pixels above, load the new content/if (document). Height ()-$ (this). ScrollTop ()-$ (this). Height ()
          ) {counter + +;
          
          Pagestart = counter * pageSize;
        Callback && callback (config, Pagestart, pageSize);

      }
      });
    /* First automatic loading/callback && Callback (config, Pagestart, pageSize);
}, $.loadmore = Loadmore; (Window, window.jquery | | | window.)

 Zepto);

How to use it? Very simple:

$.loadmore.get (GetData, {
  scroll:true,//default is False, support for scrolling load
  size:7,//default is
  flag:1,//custom parameters, optional, not used in the example
});

The first parameter is the callback function, which is our business logic. I posted the last modified business logic method:

function getData (config, offset,size) {Config.isajax = true; $.ajax ({type: ' Get ', url: ' Json/blog.json ', DataType: ' JSON ', Success:function (reponse) {conf

      Ig.isajax = false;
      var data = reponse.list;
      
      var sum = reponse.list.length;
      
      var result = ';
      
      /************ business logic BLOCK: To achieve the mosaic HTML content and append to the page *****************///console.log (offset, size, sum); * * If the remaining number of records is not enough paging, let the number of pages to take the remaining records * For example, the page is 5, only 2, then only 2 * * * * actual mysql query does not write this * * * Sum-offset <
      Size) {size = Sum-offset; /* Use the For loop to simulate limit (offset,size)/for (Var I=offset; i< (offset+size); i++) {results = = '  <div class= "Weui_media_box weui_media_text" > ' + ' <a href= "' + Data[i].url + '" target= "_blank" >

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.