Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions src/scripts/main.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,32 @@
'use strict';

document.addEventListener('click', (e) => {
// write code here
// eslint-disable-next-line no-shadow
document.addEventListener('click', (event) => {
const wall = document.querySelector('.wall');
const spider = document.querySelector('.spider');

if (event.target !== wall && event.target !== spider) {
return;
}

const wallRect = wall.getBoundingClientRect();
const spiderRect = spider.getBoundingClientRect();
const spiderW = spiderRect.width;
const spiderH = spiderRect.height;
const borderWidth = parseInt(getComputedStyle(wall).borderLeftWidth);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line assumes all borders of the wall have the same width as the left border. This will cause incorrect positioning if, for example, border-top-width is different. The clickY calculation on line 19 and the boundary calculations on lines 23 and 27 will be wrong. It's better to get each border width property (borderTopWidth, borderRightWidth, borderBottomWidth) and use them in their respective calculations.


const clickX = event.clientX - wallRect.left - borderWidth;
const clickY = event.clientY - wallRect.top - borderWidth;

const x = Math.min(
Math.max(clickX - spiderW / 2, 0),
wallRect.width - spiderW - borderWidth * 2,
);
const y = Math.min(
Math.max(clickY - spiderH / 2, 0),
wallRect.height - spiderH - borderWidth * 2,
);

spider.style.left = `${x}px`;
spider.style.top = `${y}px`;
});
Loading