-
Notifications
You must be signed in to change notification settings - Fork 0
/
pagination.js
79 lines (71 loc) · 2.28 KB
/
pagination.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
$(function() {
var container = $('.container').eq(0)
if (container.length === 0) return
if (container.children('hr').length === 0) return
var _pages = splitPages(container.contents())
setupPager()
makePagination(_pages)
function splitPages(nodes) {
var result = []
var current = null
nodes.each(function() {
var $this = $(this)
if ($this.is('h1')) return
if ($this.is('hr')) {
if (current != null) {
current.append($this)
result.push(current)
current = null
}
} else {
if (current == null && this.nodeType == 1) {
current = $('<div class="page"></div>').insertBefore($this)
}
if (current != null) {
current.append($this)
}
}
})
if (current != null) {
result.push(current)
current = null
}
return result
}
function makePagination(pages) {
var page
var all = $(pages).map(function() { return this.toArray() })
var current = all
$(window).on('hashchange', function() {
updatePage()
})
updatePage()
function updatePage() {
var target = extractPageNumber()
if (page == target) return
if (current) current.hide()
current = pages[target - 1]
if (current) current.show()
page = target
$(document).triggerHandler('pagination', [{ page: page, pages: pages }])
}
function extractPageNumber() {
var match = (location.hash).match(/\d+/)
return (match && parseInt(match[0], 10)) || 1
}
}
function setupPager() {
var el = $('<ul class="pager"><li class="prev-li"><a href="javascript://" class="prev-link">Previous</a></li> <li class="next-li"><a href="javascript://" class="next-link">Next →</a></li></ul>').appendTo('.container')
var prev = el.find('.prev-link')
var next = el.find('.next-link')
$(prev).add(next).on('click', function() {
window.scrollTo(0, 0)
})
$(document).on('pagination', function(event, info) {
el.find('.prev-li').toggleClass('disabled', !!(info.page == 1))
el.find('.next-li').toggleClass('disabled', !!(info.page == info.pages.length))
prev.attr('href', '#' + Math.max(1, info.page - 1))
next.attr('href', '#' + Math.min(info.pages.length, info.page + 1))
})
}
})