jqlearner
jqlearner

Reputation: 23

Count Divs and Hide some

I have a dynamic page which has a parent div called 'divWiz' where I have to do the following:

If the user clicks the 'Show Next' link, the first 25 should be hidden and the next 25 visible. 'Show Next' link should be invisible now.

If the user clicks 'Show All', all the div's should be visible. Both the links will disappear once the user clicks Show All.

How can I do this? Since this involves lot of traversing, I am looking for jquery code with performance.

Upvotes: 2

Views: 978

Answers (4)

Peter Ajtai
Peter Ajtai

Reputation: 57695

You can make use of the index numbers:

$('#divWiz > div:lt(25)')          // all divs of index 0 to 24

$('#divWiz > div:lt(50):gt(24)')  // all divs of index 25 to 49

Caution! :gt(-1) doesn't work!

So, here's a quick and dirty full working example of something like what you're describing:

HTML:

<input value=" Next " type="button"/>
<input value=" Prev " type="button"/>
<input value=" Show All " type="button"/>
<div id="divWiz"></div>

JS:

$(function() {
    var i, cutoff, total = 50;
    for(i=0; i<total; ++i)
        $(document.createElement("div")).html(i).appendTo("#divWiz");

    cutoff = total/2;

    $("#divWiz > div").hide();
    $("#divWiz > div:lt("+cutoff+")").show();

    $("input[value=' Next ']").click(function() {       
        $("#divWiz > div").hide();        
        $("#divWiz > div:gt("+(cutoff - 1)+")").show();
    });

    $("input[value=' Prev ']").click(function() {       
        $("#divWiz > div").hide();        
        $("#divWiz > div:lt("+cutoff+")").show();    });    

    $("input[value=' Show All ']").click(function() {       
        $("#divWiz > div").show();        
    });        
});

Try it out with this jsFiddle

Upvotes: 0

Dr.Molle
Dr.Molle

Reputation: 117354

jQuery wont give you more performance, it will give you an easier way to implement. If you need better performance, wrap those "packs" of 25 div's into common parents and show/hide those parents(should be 25 times faster)

Upvotes: 1

tobyodavies
tobyodavies

Reputation: 28099

all you need to do is have onclick handlers that show/hide either firstHalf, secondHalf or both.

var divCount   = $('#divWiz>div').length;
var firstHalf  = $('#divWiz>div').slice(0,divCount/2);
var secondHalf = $('#divWiz>div').slice(divCount/2);

Upvotes: 1

casablanca
casablanca

Reputation: 70711

Here are some hints to get you started:

  • $('#divWiz > div') will get you all the DIVs within "divWiz".
  • $(something).length is the number of selected elements.
  • $(something).slice(start, end) lets you operate on a subset of selected elements.

You should be able to put these together to do what you want.

Upvotes: 2

Related Questions