summaryrefslogtreecommitdiff
path: root/article.js
blob: 4818a3ddfad9cda1f9816941097c21b384754c44 (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
46
47
48
49
50
51
52
53
function addTOC() {
    var tocDiv = document.createElement("div");
    tocDiv.classList += "toc";
    var toc = document.createElement("ul");

    document.body.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach(heading => {
        var link = document.createElement('a');
        link.setAttribute('href', '#'+heading.id.toLowerCase());
        link.textContent = heading.textContent;
        
        var li = document.createElement('li');
        li.appendChild(link);
        
        toc.appendChild(li);
    });

    tocDiv.append(toc);
    document.body.prepend(tocDiv);

    var styleBlock = document.createElement("style");
    styleBlock.textContent = `
        .toc {
            position: fixed;
            width: 17rem;
            top: 32px;
            left: calc(50vw - 37.5ch - 20rem);
            padding-right: 0.75rem;
            z-index: 1;

            ul {
                margin: 0;
                padding-left: 1rem;
                line-height: 1.4;
            }

            li {
                margin-bottom: 0.35rem;
                font-size: 1.1rem;
            }
        }

        @media (max-width: 1000px) {
            .toc {
                display: none;
            }
        }
    `;
    document.head.append(styleBlock);
}

document.addEventListener("DOMContentLoaded", () => {
    addTOC()
})