简体   繁体   中英

Show a number of additional divs on every click

I want to have a sequential list display, where initially all the lis except the first one are hidden, and when the user clicks a button, the lis appear by groups of 3. Eventually I would like to hide the button when the list gets to the end.

The code is something like this, but it shows only one per click, every third - but I want to show also the in-between elements until the third

jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
    e.preventDefault();
    i+=3;
    jQuery(".event-holder").eq(i).fadeIn();
    if ( i == numbofelem ) { jQuery(this).hide(); }
});

Probably the .eq(i) is not the function I need, but couldn't find the correct one...

Working fiddle

If you have just three you could use :

jQuery(".event-holder:gt(0)").hide();

var i = 0;
var numbofelem = jQuery(".event-holder").length;
var li = jQuery(".event-holder");

jQuery("#allevents").on('click', function(e){
    e.preventDefault();

    li.eq(i+1).fadeIn();
    li.eq(i+2).fadeIn();
    li.eq(i+3).fadeIn();

    i+=3;

    if ( i == numbofelem ) { jQuery(this).hide(); }
});

If you have several li s to show you could use a loop, eg :

var step = 10; //Define it outside of the event

for(var j=0;j<step;j++){
    li.eq(i+j).fadeIn();
}

i+=step;

Hope this helps.

You can use :hidden with use of .each() loop:

jQuery("#allevents").on('click', function(e){
    e.preventDefault();
    jQuery(".event-holder:hidden").each(function(i){
        if(i <= 2){
         jQuery(this).fadeIn();
        }
    });
});

You eq(i) needs to be looped.

jQuery(".event-holder:gt(0)").hide();
var i = 0;
var numbofelem = jQuery(".event-holder").length;
jQuery("#allevents").on('click', function(e){
    e.preventDefault();
    //i+=3;
    //jQuery(".event-holder").eq(i).fadeIn();//You are showing only the third element. Loop this
    //Something like this
    for(var j=i;j<i+3;j++){
      jQuery(".event-holder").eq(i).fadeIn();
      if ( i == numbofelem ) { jQuery(this).hide(); }
    }
    i = j;
});

An alternative approach would be to buffer all the items, and keep adding them until empty:

var holders = $('.event-holder').hide();

$("#allevents").click( function(e){
    e.preventDefault();  
    holders = holders.not(holders.slice(0, 3).fadeIn());
    if(holders.length === 0) $(this).hide();
});

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM