-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
41 lines (27 loc) · 1.04 KB
/
script.js
File metadata and controls
41 lines (27 loc) · 1.04 KB
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
var box = document.getElementById("box");
var viewWidth = window.innerWidth;
var viewHeight = window.innerHeight;
// Updates the viewport height and width dynamically
window.addEventListener("resize", function(event) {
viewWidth = window.innerWidth;
viewHeight = window.innerHeight;
});
box.addEventListener("mouseover", function(event) {
var boxAttr = box.getBoundingClientRect();
var pos = getNewPosition(boxAttr.width, boxAttr.height);
box.style.top = pos.y + "px";
box.style.left = pos.x + "px";
});
function getNewPosition(boxWidth, boxHeight) {
// The boxWidth and boxHeight are subtracted so that they would not move out from the right and bottom direction
var newX = Math.floor((Math.random() * viewWidth) + 1 - boxWidth);
var newY = Math.floor((Math.random() * viewHeight) + 1 - boxHeight);
// These will satisfy that box does not move go out in the top and left direction
if(newX < 0) {
newX = 0;
}
if(newY < 0) {
newY = 0;
}
return {x: newX, y: newY};
}