I am making a chrome extension which puts an emoji shmeji into your site.
When i made a function that checks if X,Y position is colliding with element,
It only returns false.
But its actually colliding with some of HTML elements.
How can i fix it?
Heres my code:
var emoji = document.createElement('span');
// ...
var hold = false;
var emojix = Math.round(window.innerWidth / 2);
var emojiy = Math.round(window.innerHeight / 2);
var emojively = 0;
var emojivelx = 0;
var emojis = ["😃","😄","😉","😊","☺","😎","😢","😱","😖", "🙂", "🙂", "🙂", "🙂", "🙂"];
var skip = false
// ...
function htmlcol(x, y) {
var elements = document.querySelectorAll('body *'); // Get all elements within the body
for (var i = 0; i < elements.length; i++) {
var rect = elements[i].getBoundingClientRect(); // Get the boundaries of the element
if (
x >= rect.left &&
x <= rect.right &&
y >= rect.top &&
y <= rect.bottom
) {
return true
break
} else {
return false}
}
}
function update() {
// ...
if (chckycol(emojiy) || htmlcol(emojix, emojiy)) {
emojively = 0;
} else {
if (!hold) {
emojively += 0.07;
} else {
emojively = 0;
}
}
// ...
}
// ...
updates = setInterval(update,10);
2
Answers
I just found out that the htmlcol was thinking that emoji was on emoji element (itself)
And also i putted
return false
into the end of loop.And it worked like normal.
htmlcol starts looping over every element descended from the body.
It tests the first element and then either returns true or false.
This exits the function, terminating the loop in the process.
It never checks the second element.
Only return when you want to exit the loop. (You probably want to move the return false to after the loop).