-
Notifications
You must be signed in to change notification settings - Fork 15
/
Color Nearest Link.js
71 lines (60 loc) · 1.97 KB
/
Color Nearest Link.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
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
function colorNearestLink() {
var mousePosition,
currentLink,
newStyle = document.createElement("style");
newStyle.type = "text/css";
newStyle.innerHTML = ".nearestLink { background: yellow; }";
document.getElementsByTagName("head")[0].appendChild(newStyle);
window.onmousemove = handleMouseMove;
setInterval(getMousePosition, 10);
function handleMouseMove(event) {
event = event || window.event;
mousePosition = {
x: event.clientX,
y: event.clientY
};
}
function getMousePosition() {
var pos = mousePosition,
linkList,
nearest,
minDist,
currentDist,
n,
i;
if (pos) {
linkList = document.getElementsByTagName("a");
n = linkList.length;
for (i = 0; i < n; i++) {
currentDist = distance(pos, getPosition(linkList[i]));
if (!nearest) {
nearest = linkList[i];
minDist = currentDist;
} else {
if (currentDist < minDist) {
nearest = linkList[i];
minDist = currentDist;
}
}
}
if (currentLink) {
currentLink.classList.toggle("nearestLink");
}
currentLink = nearest;
currentLink.classList.toggle("nearestLink");
}
}
function getPosition(elem) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
function distance(a, b) {
return Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2);
}
}