|
| 1 | +## Pagination |
| 2 | + |
| 3 | +```html |
| 4 | +<div class="list"></div> |
| 5 | +<div class="buttons"> |
| 6 | + <button class="first">First</button> |
| 7 | + <button class="previous">Previous</button> |
| 8 | + <button class="next">Next</button> |
| 9 | + <button class="last">Last</button> |
| 10 | +</div> |
| 11 | +``` |
| 12 | + |
| 13 | +```js |
| 14 | +const list = []; |
| 15 | +const currentPageList = []; |
| 16 | +let currentPage = 1; |
| 17 | +let numOfPages = 0; |
| 18 | +let itemsPerPage = 10; |
| 19 | + |
| 20 | +const makeList = (listLength) => { |
| 21 | + for (let i = 1; i <= listLength; i++) { |
| 22 | + list.push(i); |
| 23 | + } |
| 24 | + |
| 25 | + numOfPages = Math.ceil(listLength / itemsPerPage); |
| 26 | +} |
| 27 | + |
| 28 | +const drawList = () => { |
| 29 | + const list = document.querySelector(".list"); |
| 30 | + let items = ''; |
| 31 | + |
| 32 | + for (let i = 0; i < currentPageList.length; i++) { |
| 33 | + items += 'Item-' + currentPageList[i] + '<br/>'; |
| 34 | + } |
| 35 | + |
| 36 | + list.innerHTML = items; |
| 37 | +} |
| 38 | + |
| 39 | +const updateButtons = () => { |
| 40 | + document.querySelector(".next").disabled = currentPage === numOfPages ? true : false; |
| 41 | + document.querySelector(".previous").disabled = currentPage === 1 ? true : false; |
| 42 | +} |
| 43 | + |
| 44 | +const loadList = (currentPage) => { |
| 45 | + let start = (currentPage - 1) * itemsPerPage; |
| 46 | + let end = start + itemsPerPage; |
| 47 | + |
| 48 | + currentPageList = list.slice(start, end); |
| 49 | + drawList(); |
| 50 | + updateButtons(); |
| 51 | +}; |
| 52 | + |
| 53 | +const goToPage = pageNum => { |
| 54 | + currentPage = pageNum; |
| 55 | + loadList(currentPage); |
| 56 | +}; |
| 57 | + |
| 58 | +const nextPage = () => { |
| 59 | + goToPage(currentPage + 1); |
| 60 | +}; |
| 61 | + |
| 62 | +const prevPage = () => { |
| 63 | + goToPage(currentPage - 1); |
| 64 | +}; |
| 65 | + |
| 66 | +const firstPage = () => { |
| 67 | + goToPage(1); |
| 68 | +}; |
| 69 | + |
| 70 | +const lastPage = () => { |
| 71 | + goToPage(numOfPages); |
| 72 | +}; |
| 73 | + |
| 74 | +makeList(50); |
| 75 | +loadList(1); |
| 76 | + |
| 77 | +const nextButton = document.querySelector(".next"); |
| 78 | +const prevButton = document.querySelector(".previous"); |
| 79 | +const firstButton = document.querySelector(".first"); |
| 80 | +const lastButton = document.querySelector(".last"); |
| 81 | + |
| 82 | +nextButton.addEventListener('click', nextPage); |
| 83 | +prevButton.addEventListener('click', prevPage); |
| 84 | +firstButton.addEventListener('click', firstPage); |
| 85 | +lastButton.addEventListener('click', lastPage); |
| 86 | +``` |
0 commit comments