Canvas
Canvas

Reputation: 5897

Jquery hide list of divs and show in sections of 5

I have myself a html page like so

<div id="main">
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
    <div class="content">
        <p>Text</p>
    </div>
</div>

So what I have already is in my document ready function I have this.

var sections = $(".content");
        for(var i = 0; i < sections.length; i+=5) {
            sections.slice(i, i+5).wrapAll("<div class='section-of-content'></div>");
        }

This splits my divs up and wraps them in a new div with the class "section-of-content", now what I would like to do is simply show the first "section-of-content" and hide all the others, then I will have an anchor tag at the bottom which is next and previous which will show and hide the other "section-of-content".

I have tried this

var contentSections = $(".section-of-content");
        for(var i = 0; i < contentSections.length; i++)
        {
            if(i == 0)
            { 
                contentSections [i].show();
            }
            else
            {
                contentSections [i].hide();
            }
        }

But it states that a function is undefined, it is referring to .show(); Can anyone help me out?

Upvotes: 0

Views: 152

Answers (1)

neo
neo

Reputation: 579

You have to wrap projectSections[i] in jquery selector because projectSections[i] gives you a javascript element and not a jquery object, so if you use it like:

var projectSections = $(".project-section");
for(var i = 0; i < projectSections.length; i++)
{
    if(i == 0)
    { 
        $(projectSections[i]).show();
    }
    else
    {
        $(projectSections[i]).hide();
    }
}

it would work no problem. but I suggest you use this instead:

$(".project-section").hide();
$(".project-section:first-child").show();

it's more practical.

Upvotes: 3

Related Questions