-
Notifications
You must be signed in to change notification settings - Fork 7
/
print_elements.js
75 lines (65 loc) · 2.27 KB
/
print_elements.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
var PrintElements = (function () {
"use strict";
var hideFromPrintClass = "pe-no-print";
var preservePrintClass = "pe-preserve-print";
var preserveAncestorClass = "pe-preserve-ancestor";
var bodyElementName = "BODY";
var _hide = function (element) {
if (!element.classList.contains(preservePrintClass)) {
element.classList.add(hideFromPrintClass);
}
};
var _preserve = function (element, isStartingElement) {
element.classList.remove(hideFromPrintClass);
element.classList.add(preservePrintClass);
if (!isStartingElement) {
element.classList.add(preserveAncestorClass);
}
};
var _clean = function (element) {
element.classList.remove(hideFromPrintClass);
element.classList.remove(preservePrintClass);
element.classList.remove(preserveAncestorClass);
};
var _walkSiblings = function (element, callback) {
var sibling = element.previousElementSibling;
while (sibling) {
callback(sibling);
sibling = sibling.previousElementSibling;
}
sibling = element.nextElementSibling;
while (sibling) {
callback(sibling);
sibling = sibling.nextElementSibling;
}
};
var _attachPrintClasses = function (element, isStartingElement) {
_preserve(element, isStartingElement);
_walkSiblings(element, _hide);
};
var _cleanup = function (element, isStartingElement) {
_clean(element);
_walkSiblings(element, _clean);
};
var _walkTree = function (element, callback) {
var currentElement = element;
callback(currentElement, true);
currentElement = currentElement.parentElement;
while (currentElement && currentElement.nodeName !== bodyElementName) {
callback(currentElement, false);
currentElement = currentElement.parentElement;
}
};
var _print = function (elements) {
for (var i = 0; i < elements.length; i++) {
_walkTree(elements[i], _attachPrintClasses);
}
window.print();
for (i = 0; i < elements.length; i++) {
_walkTree(elements[i], _cleanup);
}
};
return {
print: _print
};
})();