-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbutton.js
More file actions
75 lines (66 loc) · 1.85 KB
/
button.js
File metadata and controls
75 lines (66 loc) · 1.85 KB
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
/**
* An object containing a configuration for the Button constructor.
* @typedef {object} ButtonConfig
* @property {Function} down - Gets called when the button is pressed.
* @property {Function} up - Gets called when the button is released.
* @property {boolean} log - Debug output iff a callback is not set.
*/
/**
* A simple button that works well for touch devices and local debugging.
* @param {HTMLElement|string} el - The HTML container element or its ID.
* @param {Object} opts - Constructor config.
* @constructor
*/
function Button(el, opts) {
var me = this;
opts = opts || {}
var log_cb = function(name) {
return function () {
if (!opts.log) {
return;
}
if (window.console && window.console.log) {
window.console.log("button.js " + name);
}
};
};
me.down_cb = opts["down"] || log_cb("down");
me.up_cb = opts["up"] || log_cb("up");
if (typeof el == "string") {
el = document.getElementById(el);
}
me.container = el;
me.container.addEventListener("touchstart", function(e) {
me.down();
e.preventDefault();
});
me.container.addEventListener("touchmove", function(e) {
e.preventDefault();
});
me.container.addEventListener("touchend", function(e) {
me.up();
e.preventDefault();
});
if (!("ontouchstart" in document.createElement("div"))) {
me.container.addEventListener("mousedown", function(e) {
me.down();
});
me.container.addEventListener("mouseup", function(e) {
me.up();
})
}
}
/**
* Gets called when the button is pressed.
*/
Button.prototype.down = function() {
this.container.className += " button-active";
this.down_cb();
};
/**
* Gets called when the button is released.
*/
Button.prototype.up = function() {
this.container.className = this.container.className.replace(/ button\-active/g, "");
this.up_cb();
};