-
Notifications
You must be signed in to change notification settings - Fork 1
/
toggler.js
99 lines (81 loc) · 2.25 KB
/
toggler.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/*
* Ben Postlethwaite
* July 2013
* MIT
*/
module.exports = function (tag) {
var unselector = curry(toggleClass, tag, false)
var selector = curry(toggleClass, tag, true)
var group = []
var lnode = {}
function toggleNode(node, classLink, cb) {
var links = nodeArray(document.querySelectorAll('.'+classLink))
group.push({node:node, links:links})
node.addEventListener('click', function () {
var toggled = toggleClass(tag, null, node)
if (toggled) {
/*
* Unselect other nodes and their linked nodes
*/
group.forEach( function (lnode) {
unselector(lnode.node)
lnode.links.map(unselector)
})
/*
* Reselect node and it's links
*/
toggleClass(tag, true, node)
if (links)
links.map(selector)
} else {
/*
* Unselect all linked nodes
*/
if (links)
links.map(unselector)
}
/*
* If user supplied a callback, call it with toggled state
*/
if (cb) cb(toggled)
})
}
group.toggleNode = toggleNode
return group
}
function nodeArray (nodelist) {
var nodeArray = []
for (var i = 0; i < nodelist.length; ++i)
nodeArray[i] = nodelist[i]
return nodeArray
}
function toggleClass (className, bool, elem) {
/*
* Toggles class on or off depending on its state
* If "bool" is true: Only toggles to "on" state
* If "bool" is false: Only toggles class off.
* Set "bool" to null to get usual behaviour
*/
var index = elem.className.indexOf(className)
if ( (index >= 0) && (bool !== true) ) {
elem.className = cut(elem.className, index, index + className.length)
if (elem.className.slice(-1) === ' ')
elem.className = elem.className.slice(0, -1)
index = false
}
else if ( (index < 0) && (bool !== false) ) {
elem.className = elem.className ? (elem.className + " " + className) : className
index = true
}
return index
}
function cut(str, cutStart, cutEnd){
return str.substr(0,cutStart) + str.substr(cutEnd+1)
}
var curry = function (fn) {
var slice = [].slice,
args = slice.call(arguments, 1)
return function () {
return fn.apply(this, args.concat(slice.call(arguments)))
}
}