Reputation: 53
my code :
<div class="list">
<ul id="myList1">
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
</ul>
<a id="loadMore">Load more</a>
</div>
<div class="list">
<ul id="myList2" style="display: none;">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<a id="loadMore">Load more</a>
</div>
<ul>
id could be mylist2, mylist3, 4, 5 and more.
take a look my work so far :
$(document).ready(function () {
$('#myList li').hide();
size_li = $("#myList li").size();
x=3;
$('#myList li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+5 <= size_li) ? x+5 : size_li;
$('#myList li:lt('+x+')').show();
});
});
it is just to work with static selector. I still can't figure it out how can I put dynamic selector inside jquery script based on <ul id="mylist1 etc">
and may also on <a id="loadMore">Load more</a>
to handle click event.
this is the fiddle
Upvotes: 0
Views: 967
Reputation: 4560
id
attribute value should be unique in a scope of document, so reason of your problem lies in a fact that you're using id="loadMore"
instead of e.g. class name class="loadMore"
.
Your code is also relatively complicated, it can be much simpler if you will use power of jQuery DOM traversal and filtering capabilities:
$(document).ready(function () {
// Taking all UL inside lists
$('.list > ul').each(function(){
// Hiding all list elements except first 3
$(this).find('li').slice(3).hide();
});
// Handling clicks to "load more" links
$('.loadMore').on('click', function() {
// Searching for previous UL in it
var $list = $(this).prev('ul');
// Taking next 5 hidden items and displaying them
$list.find('li:hidden').slice(0,5).show();
// If last list item is already visible - hide "load more" link
if ($list.find('li:last-child').is(':visible')) {
$list.next('.loadMore').hide();
}
})
});
.loadMore {
color:green;
cursor:pointer;
}
.loadMore:hover {
color:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="list">
<ul id="myList">
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
<li>f</li>
<li>g</li>
<li>h</li>
<li>i</li>
<li>j</li>
<li>k</li>
<li>l</li>
<li>m</li>
<li>n</li>
<li>o</li>
</ul>
<a class="loadMore">Load more</a>
</div>
<div class="list">
<ul id="myList2">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
</ul>
<a class="loadMore">Load more</a>
</div>
Upvotes: 1
Reputation: 3
If I understand correctly, you need to use one button to show 5 more more li items each time you press it.
In that case I would do something like this
$('#loadMore').click(function () {
var numberOfLisToShow = 5; //for example
for(var i = 0; i < numberOfLisToShow; i++) {
//find last visible item and get the next item
$("ul#yourId li:visible:last").next().show();
}
});
but first try to hide your elements with css not javascript and make sure you leave at least one visible
Upvotes: 0