Skip to content

Instantly share code, notes, and snippets.

@tlimpanont
Last active August 29, 2015 14:03
Show Gist options
  • Save tlimpanont/56677d257e3ee17b0e02 to your computer and use it in GitHub Desktop.
Save tlimpanont/56677d257e3ee17b0e02 to your computer and use it in GitHub Desktop.
How to devide items into sections with array.slice method
<!-- I want to devide this itemList in to 3 sections. Each section should contain max 2 items.
#Section 1
<li>1</li>
<li>2</li>
#Section 2
<li>3</li>
<li>4</li>
#Section 3
<li>5</li>
-->
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
jQuery(function () {
var totalItems = jQuery("li").size();
var itemsPerPage = 2;
var sectionsCount = Math.ceil(totalItems / itemsPerPage);
for (var i = 0; i < sectionsCount; i++) {
var color = '#' + Math.floor(Math.random() * 16777215).toString(16);
jQuery("li")
.slice(i * itemsPerPage, itemsPerPage + i * itemsPerPage)
.each(function (index, li) {
jQuery(this).css({
background: color
});
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment