Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select hidden elements and manipulate them with jQuery

Within a div wrapper with a class of "section", I have dozens of HTML elements repeated across the page that look like this:

<div class="section">
  <div class="article"></div>
  <div class="article"></div>
  <div class="article"></div>
</div>

And each contains certain information inside. Now, what I'm trying to do is once the page loads, show only the first 5, hide the rest in a new div inserted with jQuery, and when this new div is clicked it will display the next five , and then the next five on click again, and so on until the end. The idea is that this new div will function as a button that will always be positioned at the end of the page and will respond to these orders I just mentioned. So far I've got this down:

$('.section').each(function () {
    var $this = $(this),
        $allArticles = $this.find('.article');

    if ($allArticles.length > 5) {
        $('<div/>').addClass('hidden-articles').appendTo(this).append($allArticles.slice(5));
        $('.hidden-articles .article').hide();
    }
});

And that hides all but the first five. But now for the rest of the process, I can't get it to work. I don't seem to be able to select properly those hidden div with class "article" and manipulate them to function the way I described above. I would appreciate it a lot if someone more experienced with jQuery could guide me in the right direction and maybe offer a snippet. Many thanks in advance!

like image 920
Blueshift Avatar asked Nov 04 '22 08:11

Blueshift


1 Answers

You can use the :hidden and :lt selectors to get the functionality you are looking for..

$('.section').each(function() {
    var $this = $(this),
        $allArticles = $this.find('.article');

    if ($allArticles.length > 5) {
        $('<div/>').addClass('hidden-articles')
                   .appendTo(this).append($allArticles.slice(5));
        $this.find('.hidden-articles .article').hide();

    }
});

$('#show').on('click',function() {
    var $hidden = $('.hidden-articles .article:hidden:lt(5)');
    $hidden.show();
});​

UPDATE

// If one one element to search 
var elem = '.section' ;
hideArticles(elem);

// If Multiple Elements on the page...
$('.section').each(function() {
    hideArticles(this);
});

$('#show').on('click', function() {
    var $hidden = $('.hidden-articles .article:hidden:lt(5)');
    $hidden.show();
});

function hideArticles(elem) {
    var $this = $(elem),
        $allArticles = $this.find('.article');

    if ($allArticles.length > 5) {
        $('<div/>').addClass('hidden-articles')
                   .appendTo(this).append($allArticles.slice(5));
        $this.find('.hidden-articles .article').hide();
    }
}​

Check Fiddle

like image 154
Sushanth -- Avatar answered Nov 08 '22 08:11

Sushanth --