-
Notifications
You must be signed in to change notification settings - Fork 646
/
Copy pathdetails-force-state.js
41 lines (35 loc) · 1.01 KB
/
details-force-state.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
(function() {
if( !("querySelectorAll" in document) || !("from" in Array) ) {
return;
}
// This is a var, `let` caused an error in Safari 13
var attr = {
base: "data-force-state",
forceState: "data-force-state-closed",
};
function forceState(detail, isOpen) {
if( isOpen ) {
detail.setAttribute("open", "open");
} else {
detail.removeAttribute("open");
}
}
function getMatchMedia(detail) {
if(!detail) return;
let forceClosed = detail.getAttribute(attr.forceState);
if(forceClosed && "matchMedia" in window) {
return window.matchMedia(forceClosed);
}
}
let details = Array.from(document.querySelectorAll(`details[${attr.base}]`));
for(let detail of details) {
let mm = getMatchMedia(detail);
if( mm ) {
forceState(detail, !mm.matches);
// Force stated based on details-force-state-closed attribute value in a media query listener
mm.addListener(function(e) {
forceState(detail, !e.matches);
});
}
}
})();