summaryrefslogtreecommitdiff
path: root/html/assets/js/plugins/tooltip.js
blob: 2326caff79f6c21a97f100ca2c8c1ea27be8c499 (plain)
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
$$plugins.define('tooltip', ['throttle'], function (element, options, throttle) {
    var openBtn = element.querySelector('.tooltip__btn'),
        tooltipMain = element.querySelector('.tooltip__main');

    openBtn.addEventListener('click', (event) => {
        event.preventDefault();
        if (element.classList.contains('tooltip--open')) {
            element.classList.remove('tooltip--open');
        } else {
            $('.tooltip').not(element).removeClass('tooltip--open');
            element.classList.add('tooltip--open');
        }
    });

    document.addEventListener('click', function (event) {
        if (element !== event.target && !element.contains(event.target) && element.classList.contains('tooltip--open')) {
            element.classList.remove('tooltip--open');
        }
    });

    function tooltipPosition() {
        element.classList.remove('tooltip--bottom');
        element.classList.remove('tooltip--right');
        element.classList.remove('tooltip--left');

        if (element.getBoundingClientRect().top < window.innerHeight / 2) {
            element.classList.add('tooltip--bottom');
        } else {
            element.classList.remove('tooltip--bottom');
        }

        if (element.getBoundingClientRect().left < tooltipMain.offsetWidth / 2) {
            element.classList.add('tooltip--right');
        }

        if (document.body.clientWidth - element.getBoundingClientRect().left < tooltipMain.offsetWidth / 2) {
            element.classList.add('tooltip--left');
        }
    }

    tooltipPosition();

    window.addEventListener('scroll', throttle(tooltipPosition, 50));
    window.addEventListener('resize', throttle(tooltipPosition, 200));
});