aboutsummaryrefslogtreecommitdiff
path: root/hovercard.js
blob: c8bd4911a8415680351caa177678135d6adca6f0 (plain) (blame)
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 curURL = document.URL
var baseURL = document.domain

// these will not attempt to get fetched, so can be used to override things
var hovercards = {
  curURL : {},
  baseURL: {}
};

var article = document.getElementsByTagName("article");

  if (article) {
    article = article[0];
  }

  function hover (target_link) {
    var hovercard_data = hovercards[target_link.href.replace(/\/+$/, "")];
    if (hovercard_data) {
      var new_box = document.createElement("div");
      new_box.classList.add("hovercard");
      new_box.innerHTML = "<strong>" + hovercard_data["title"] + "</strong>"
      if (hovercard_data["description"]) {
        new_box.innerHTML = new_box.innerHTML + "<p>" + hovercard_data["description"] + "</p>";
      }
      // if image available, add it
      if (hovercard_data["image"]) {
        new_box.innerHTML = "<img src='" + hovercard_data["image"] + "' alt='" + hovercard_data["title"] + "' /><br>" + new_box.innerHTML;
      }
      new_box.style.top = window.scrollY + target_link.getBoundingClientRect().top + "px";
      new_box.style.left = window.scrollX + target_link.getBoundingClientRect().left + "px";
      new_box.id = "tooltip";
      document.body.appendChild(new_box);
    }
  }

  function unhover (target_link) {
    var active_hovercard = document.getElementById("tooltip");

    if (active_hovercard) {
      active_hovercard.parentNode.removeChild(active_hovercard);
    }
  }

  var links = article.getElementsByTagName("a");

  for (var i = 0; i < links.length; i++) {
    links[i].addEventListener("mouseover", function() {
      hover(this);
    });
    links[i].addEventListener("mouseout", function() {
      unhover(this);
    });
    // these handlers are so that the hovercard will appear/disappear
    // with keyboard actions
    links[i].addEventListener("onfocus", function() {
      hover(this);
    });
    links[i].addEventListener("onfocusout", function() {
      unhover(this);
    });
    let url = links[i].href.replace(/\/+$/, "");
    if (!hovercards[url]) {
      let req = 'https://indieweb-glue.evgenykuznetsov.org/api/opengraph?url=';
      req += url;
      const r = encodeURI(req);
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          hovercards[url] = JSON.parse(this.responseText);
        }
      };
      xmlhttp.open("GET", r, true);
      xmlhttp.send();
    }
  }