"use strict"
;
class Popover {
constructor(element, trigger, options) {
this
.options = {
position: Popover.BOTTOM,
};
this
.element = element;
this
.trigger = trigger;
this
._isOpen =
false
;
Object.assign(
this
.options, options);
this
.events();
this
.initialPosition();
}
events() {
this
.trigger.addEventListener(
"click"
,
this
.toggle.bind(
this
)
);
}
initialPosition() {
let triggerRect =
this
.trigger.getBoundingClientRect();
this
.element.style.top = ~~triggerRect.top +
"px"
;
this
.element.style.left = ~~triggerRect.left +
"px"
;
}
toggle(e) {
e.stopPropagation();
if
(
this
._isOpen) {
this
.close(e);
}
else
{
this
.element.style.display =
"block"
;
this
._isOpen =
true
;
this
.outsideClick();
this
.position();
}
}
targetIsInsideElement(e) {
let target = e.target;
if
(target) {
do
{
if
(target ===
this
.element) {
return
true
;
}
}
while
((target = target.parentNode));
}
return
false
;
}
close(e) {
if
(!
this
.targetIsInsideElement(e)) {
this
.element.style.display =
"none"
;
this
._isOpen =
false
;
this
.killOutSideClick();
}
}
outsideClick() {
document.addEventListener(
"click"
,
this
.close.bind(
this
)
);
}
killOutSideClick() {
document.removeEventListener(
"click"
,
this
.close.bind(
this
)
);
}
isOpen() {
return
this
._isOpen;
}
}
Popover.TOP =
"top"
;
Popover.RIGHT =
"right"
;
Popover.BOTTOM =
"bottom"
;
Popover.LEFT =
"left"
;
document.addEventListener(
"DOMContentLoaded"
,
function
() {
let btn = document.querySelector(
"#popoverOpener button"
),
template = document.querySelector(
".popover"
),
pop =
new
Popover(template, btn, {
position: Popover.RIGHT,
}),
links = template.querySelectorAll(
".popover-content a"
);
for
(let i = 0, len = links.length; i < len; ++i) {
let link = links[i];
console.log(link);
link.addEventListener(
"click"
,
function
(e) {
e.preventDefault();
pop.position(
this
.className);
this
.blur();
return
true
;
});
}
});