Use IntersectionObserver to detect div-position change - javascript

I want to observe the position of a div element that moves inside a larger container:
The page contains one div with the ID #actual which starts at a known position. Over time, the #actual div changes its position, and I need to run a function when that happens.
The #actual position can change in different ways - via CSS left/top changes, a CSS transform on a parent element, or a sibling changes size and pushes the div up/down.
My current attempt is, to add a hidden div to the page, with the ID #known which starts off at the same position as #actual. Now I try to add an IntersectionObserver that fires when the intersection between #actual and #known changes.
Here's my sample code:
const known = document.querySelector('#known');
const actual = document.querySelector('#actual');
const ioOptions = {
tolerance: 0,
root: known
};
const ioObserver = new IntersectionObserver(ioChange, ioOptions);
function ioChange(entries) {
console.log('Intersection changed:', entries[0].intersectionRect);
}
ioObserver.observe(actual);
Problem
The observer never fires. Why?
How can I get the Observer to work?
Or is there a better/different way to detect position changes of #actual?
Click below to see the full sample with the two divs:
const known = document.querySelector('#known');
const actual = document.querySelector('#actual');
// -- Intersection Observer --------
const ioOptions = {
tolerance: 0,
root: known
};
const ioObserver = new IntersectionObserver(ioChange, ioOptions);
function ioChange(entries) {
console.log('Intersection changed:', entries[0].intersectionRect);
}
ioObserver.observe(actual);
// -- Sample animation logic -----
// I expect that this animation constantly triggers the
// ioChange callback above.
// -- Sample animation logic -----
function setKnown() {
known.style.left = actual.style.left;
known.style.top = actual.style.top;
}
function moveBox() {
actual.style.left = (Math.random() * 240) + 'px';
actual.style.top = (Math.random() * 240) + 'px';
}
actual.style.left = '120px';
actual.style.top = '120px';
setKnown();
setInterval(moveBox, 1000);
#root {
position: relative;
margin: 20px auto;
background: #fff;
border: 1px solid #000;
width: 320px;
height: 320px;
box-shadow: 0 0 30px #0002;
box-sizing: border-box;
font: 14px sans-serif;
}
.box {
width: 80px;
height: 80px;
position: absolute;
text-align: center;
line-height: 80px;
white-space: nowrap;
box-sizing: border-box;
}
#known {
background: #8881;
border: 1px dashed #999;
}
#actual {
background: #0068;
color: #fff;
transition: all 0.3s;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="root">
<div id="known" class="box">Known</div>
<div id="actual" class="box">Actual</div>
</div>
</body>
</html>

I know it's an old question, but if anyone happened to come across it, just make small changes to make the example work. Instead of tolerance, you should use the treshold option exactly like this:
const ioOptions = {
treshold: 0,
root: known
};
const ioObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if(entry.isIntersecting){
ioChange(entry);
}
});
});
Working example

Related

How to Incrementally Update an Elements Scale by Pinching with Js

The below code ALMOST works and I think I'm close yet quite far away from getting it to work properly. The problem is, the way the handlePinch function is set up. What actually happens when the user pinches to zoom a bit, is the square starts to accelerate. The more the user pinches, the faster the square zooms.
How can this be implemented that each time the user pinches to zoom, it incrementally scales, i.e. picking up where it left off without exceeding the max scale?
I'm stuck on this for two days and there doesn't seem to be any formula to show how something like this works. Note, I know there are libraries for this, I want to know how this works with vanilla js
const box = document.querySelector('.box')
function updateCss(scale) {
box.style.transform = `scale(${scale})`
}
let lastScale
let currentScale
let isAlreadyScaled = false
const minScale = 1
const maxScale = 1.8
function handlePinch(e) {
e.preventDefault()
const isZooming = e.scale > 1
if (isZooming) {
if (!isAlreadyScaled) {
lastScale = Math.min(minScale * e.scale, maxScale)
isAlreadyScaled = true
} else {
lastScale = Math.min(minScale * (lastScale * e.scale), maxScale)
}
}
updateCss(lastScale)
}
box.addEventListener('touchstart', e => {
if (e.touches.length === 2) {
handlePinch(e)
}
})
box.addEventListener('touchmove', e => {
if (e.touches.length === 2) {
handlePinch(e)
}
})
* {
box-sizing: border-box;
}
body {
padding: 0;
margin: 0;
}
.wrapper {
height: 400px;
width: 100%;
top: 0;
left: 0;
position: relative;
margin: 24px;
}
.scale-container {
height: 100%;
width: 100%;
position: absolute;
background: #eee;
display: flex;
align-items: center;
justify-content: center;
}
.box {
height: 200px;
width: 200px;
background: pink;
position: absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Home</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
</head>
<body>
<div class="wrapper">
<div class="scale-container">
<div class="box"></div>
</div>
</div>
</body>
</html>

How do I add an on-delay animation and scoreboard to this little game I made

I created this color guessing game from scratch using HTML, CSS and JS. You're given a random RGB value and you guess which out of three given colors is the correct one. Now I want to take it a step higher by adding a scoreboard and score (Which I'm not sure how to do at all) and a full-screen congratulation message when you guess the color right. I've tried doing that but the animation doesn't seem to work.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1 class="text-centered" id="main-h1">Guess The Color!</h1>
<h2 class="text-centered" id="colorguess"></h2>
<p id="score">
</p>
<div class="box-container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
<div id="bravo">
<p id="bravo-text">
BRAVO
</p>
</div>
</body>
<script src="script.js"></script>
</html>
CSS
*{
box-sizing: border-box;
}
body{
font-family: arial;
background-color: #1c1874;
color: rgb(105, 105, 139);
color: #fff;
}
.text-centered{
text-align: center;
text-shadow: 0px 2px 2px rgba(150, 150, 150, 1);
}
.box-container{
padding: 200px;
align-self: center;
display: flex;
flex-direction: row;
justify-content:space-evenly;
}
.box{
width: 200px;
height: 200px;
border-radius: 20px;
cursor: pointer;
border:5px solid #ffffff;
}
#score{
font-weight: 500;
font-size: 2em;
position: fixed;
top: 5%;
left: 5%;
}
#score::before {
content: "Score: ";
}
#bravo{
position: fixed;
display: none;
opacity: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
text-align: center;
font-size: 5em;
background-color: rgba(4, 8, 97, 0.69);
}
#bravo-text{
flex: 0 0 120px;
text-shadow: 0px 2px 2px rgba(150, 150, 150, 1);
}
JS
function getrandomcolor(){
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
rgb = "rgb("+r+", "+g+", "+b+")";
return rgb;
}
function gamestart(){
var mainh1 = document.getElementById('main-h1');
mainh1.innerHTML = "Guess the color!";
rgbvaluetrue = getrandomcolor();
var rgb = document.getElementById('colorguess');
rgb.innerHTML = rgbvaluetrue;
var body = document.getElementsByTagName('body');
var box = document.getElementsByClassName('box');
var scoreboard= document.getElementById('score');
var score = 0;
function displaybravo(element){
var op= 0;
var timer = setInterval(function () {
if (op >= 1){
clearInterval(timer);
}
if(op>=0.1){
element.style.display = "flex";
element.style.flexDirection = "column";
element.style.justifyContent = "center";
element.style.alignItems="center";
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
for(var i=0;i<box.length;i++){
box[i].style.backgroundColor = getrandomcolor();
}
//here I am trying to assign the initial rgb value to one of the divs randomly
var rand = Math.floor(Math.random() * box.length);
box[rand].style.backgroundColor = rgbvaluetrue;
//here I check if the div you clicked on is correct
function markSelection() {
if(this.style.backgroundColor == rgbvaluetrue) {
mainh1.innerHTML="BRAVO";
setTimeout(function() {
var brv = document.getElementById('bravo');
displaybravo(brv);
gamestart(); }, 2000);
} else {
gamestart();
}
}
for(var i=0;i<box.length;i++){
box[i].onclick = markSelection;
}
scoreboard.innerHTML=score;
}
gamestart();
I reviewed your game and made some changes to the code based on what stood out to me. There were a few bugs that were important to correct, and many things I changed purely for readability / preference.
I tend to avoid directly using timeouts. Promises are a good way to control the order of things in javascript. This game could likely benefit from OOP to make the logic more organized, but I didn't want to return you something that was completely unrecognizable. You are welcome to take this to code review for a more complete refactoring.
The first issue that I noticed is that your setInterval never resolves with the logic implemented. Because it never resolves, every time you attempted to show the bravo message, it would start an interval at 10 ms, and they would stack on top of eachother. This quickly would become an issue, potentially even breaking your page. Instead of attempting to redesign your interval logic, I decided to use the css transition attribute to handle the Bravo message, and I threw in a keyframe animation so you could see how to add other effects without javascript. Instead of having to write logic in js and preform resource expensive operations, I can leave the animation to css. Now js just needs to add and remove the hidden class.
I also wrote a helper function wait at the top of the js, and made functions with waiting async so I could use the await keyword instead of nesting my code inside timeouts. This is more readable in my own opinion.
To add a score, I moved the score variable above the gameStart function. This way each time the game restarts, the score is not affected. Then I just had to increment the score variable whenever a correct answer is given, and change the text in the dom.
One bug I noticed was that the correct answer could have been clicked several times, and the points would have increased, because the event listener was still active after the answer was submitted. To handle this, I changed the way the event listener was applied. Instead of using element.onclick =, I opted for el.addEventListener("click", . This allowed me to use .removeEventListener once the answer was given, and only reapply the event listener once the next round started. I also added a wait for incorrect answers, and some text when the wrong answer was given.
Other more cosmetic changes include using a helper function $ to make grabbing elements easier, and changing .innerHTML to .innerText to more clearly show intent / prevent potential bugs.
I didn't correct it in this code, but it's worth mentioning variable names in javascript are usually camel case. i.e. instead of getrandomcolor it would be getRandomColor
If you have any questions about my code, please ask 👍
const wait = t => new Promise(r => setTimeout(r, t));
const $ = (str, dom = document) => [...dom.querySelectorAll(str)];
function getrandomcolor(){
const random255 = () => Math.floor(Math.random() * 256);
const [r, g, b] = Array.from({length: 3}, random255);
return "rgb(" + r + ", " + g + ", " + b + ")";
}
let scoreboard = $('#score')[0];
let score = 0;
function gamestart(){
var mainh1 = $('#main-h1')[0];
mainh1.innerText = "Guess the color!";
rgbvaluetrue = getrandomcolor();
var rgb = $('#colorguess')[0];
rgb.innerText = rgbvaluetrue;
var body = document.body;
var allBoxes = $('.box');
async function displaybravo(element){
element.classList.remove("hidden");
await wait(2000);
element.classList.add("hidden");
await wait(1000);
}
for (var i=0; i<allBoxes.length; i++) {
allBoxes[i].style.backgroundColor = getrandomcolor();
}
var randomBoxIndex = Math.floor(Math.random() * allBoxes.length);
allBoxes[randomBoxIndex].style.backgroundColor = rgbvaluetrue;
async function markSelection() {
allBoxes.forEach(box => box.removeEventListener("click", markSelection));
if (this.style.backgroundColor == rgbvaluetrue) {
score++;
scoreboard.innerText = score;
mainh1.innerText = "BRAVO";
var brv = $('#bravo')[0];
await displaybravo(brv);
gamestart();
} else {
mainh1.innerText = "NOPE!";
await wait(1000);
gamestart();
}
}
allBoxes.forEach(box => box.addEventListener("click", markSelection));
scoreboard.innerHTML = score;
}
gamestart();
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: arial;
background-color: #1c1874;
color: rgb(105, 105, 139);
color: #fff;
}
.text-centered{
text-align: center;
text-shadow: 0px 2px 2px rgba(150, 150, 150, 1);
}
.box-container{
padding: 200px;
align-self: center;
display: flex;
flex-direction: row;
justify-content:space-evenly;
}
.box{
width: 200px;
height: 200px;
border-radius: 20px;
cursor: pointer;
border:5px solid #ffffff;
}
#score{
font-weight: 500;
font-size: 2em;
position: fixed;
top: 5%;
left: 5%;
}
#score::before {
content: "Score: ";
}
#bravo {
overflow: hidden;
position: fixed;
inset: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100%; /*needed to transition to / from*/
transition: height 2s;
}
#bravo.hidden {
height: 0;
}
#bravo-text {
font-size: 5rem;
font-weight: bold;
color: black;
animation: glow 1s ease-in-out infinite alternate;
}
#keyframes glow {
from {
text-shadow:
0 0 5px #fff,
0 0 10px #fff,
0 0 15px #e60073,
0 0 20px #e60073,
0 0 25px #e60073,
0 0 30px #e60073,
0 0 35px #e60073;
}
to {
text-shadow:
0 0 10px #fff,
0 0 20px #ff4da6,
0 0 30px #ff4da6,
0 0 40px #ff4da6,
0 0 50px #ff4da6,
0 0 60px #ff4da6,
0 0 70px #ff4da6;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="main.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script defer src="main.js"></script>
</head>
<body>
<h1 class="text-centered" id="main-h1">Guess The Color!</h1>
<h2 class="text-centered" id="colorguess"></h2>
<p id="score">
</p>
<div class="box-container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
<div id="bravo" class="hidden flexCenter">
<p id="bravo-text" class="flexCenter">
BRAVO
</p>
</div>
</body>
</html>

Attempting to implement javascript on html page using Dreamweaver, (mouse tracker)

I have successfully yoinked the code using javascript to replace the cursor with an animated gif from this page (https://css-tricks.com/using-css-cursors/). I have successfully chucked her into Dreamweaver, I'm new to coding and I know it's way too much to start with but I want to make my website track the location of your cursor and change depending on which half of the page it's on. To be specific cursors derived from the painting: the creation of adam (the hands). Depending on which side it will switch between one of two cursors. I have found success in using a singular png as the cursor with the cursor: url() CSS method. This current method uses the CSS method of cursor: none in my style.css file.
The current javascript code is as follows
(function() {
var follower, init, mouseX, mouseY, positionElement, printout, timer;
follower = document.getElementById('follower');
printout = document.getElementById('printout');
mouseX = (event) => {
return event.clientX;
};
mouseY = (event) => {
return event.clientY;
};
positionElement = (event) => {
var mouse;
mouse = {
x: mouseX(event),
y: mouseY(event)
};
follower.style.top = mouse.y + 'px';
return follower.style.left = mouse.x + 'px';
};
timer = false;
window.onmousemove = init = (event) => {
var _event;
_event = event;
return timer = setTimeout(() => {
return positionElement(_event);
}, 1);
};
}).call(this);
and the style.css file is:
html {
cursor: url("Cursor222.png");
background: #E0CDA9;
}
#follower {
position: absolute;
top: 50%;
left: 50%;
}
#follower #circle1 {
position: absolute;
background: #0004D9;
border-radius: 50%;
height: 0em;
width: 0em;
margin-top: 0em;
margin-left: 0em;
}
#follower #circle2 {
position: absolute;
background: rgba(200,0,0,0.8);
border-radius: 50%;
height: 0em;
width: 0em;
margin-top: 0em;
margin-left: 0em;
}
I'm very new to CSS and javascript, I don't know the way to implement conditional terms like if and else, can someone chuck me some support. I get it's a big ask and I can compensate you for your time.
Here is a sample using an image:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.cursor-left {
/* cursor: url('url-to-image-1'), auto; */ // Add your cursor here
cursor: pointer;
}
.cursor-right {
/* cursor: url('url-to-image-2'), auto; */ // Add your cursor here
cursor: cell;
}
</style>
</head>
<body>
<img src="https://uploads1.wikiart.org/images/michelangelo/sistine-chapel-ceiling-creation-of-adam-1510.jpg" id="container" />
<script>
const containerElement = document.querySelector('#container');
containerElement.addEventListener('mousemove', e => {
const imageWidth = containerElement.width;
// const windowWidth = window.innerWidth; // for window
if (e.clientX <= imageWidth / 2) {
containerElement.classList.remove('cursor-right');
containerElement.classList.add('cursor-left');
} else {
containerElement.classList.remove('cursor-left');
containerElement.classList.add('cursor-right');
}
});
</script>
</body>
</html>
If you want to do it with the whole page and not a specific container, attach the event listener to the document(body might not work for you, you can see why here) and track the width with the commented code. You can add as much cursor styles as you like by altering the mouse tracking constraints.

How can I get and set style properties of an object that come from a class?

I have a simple animation function that simulates a button being pushed, by varying the width:
function bPress(b) {
var w = (parseFloat(b.style.width)*0.96);
if (b.style.width.substr(-1)=="%") {
var s ="%";
}
else {
var s = "em";
}
b.style.width = w +s;
b.onmouseup = function () {
w = (parseFloat(b.style.width)/0.96);
b.style.width = w+s;
// etc.
}
This was working well until I started cleaning up my code and changed inline CSS style declarations to classes. I previously had, for example:
<div style= 'height: 1.5em; width: 100%; margin: 0 auto; margin-top: 0.2em; font: inherit; font-weight:bold' onclick='checkSave("continue")' onmousedown='bPress(this)'>Continue</div>
I moved the CSS parts to a new class:
.response_button {
height: 1.5em;
width: 100%;
margin: 0 auto;
margin-top: 0.2em;
font: inherit;
font-weight:bold
}
... avoiding repetition and of course simplifying the div tags.
But the animations stopped working. After some experimenting, I eventually came up with a temporary solution by moving the width back into an inline style declaration. But this seems wrong.
So 2 questions:
Why does this.style.width not work if the width is declared inside a class?
Is there a way to get and set a div's properties if they are declared inside a class?
Edit: For completeness, using nick zoum's answer, here is the modified bPress function:
function bPress(b) {
var w_px = window.getComputedStyle(b).width;
var w_int = (parseInt(w_px));
b.style.width = Math.round(w_int * 0.96) + "px";
b.onmouseup = function () {
b.style.width = w_px;
}
}
You can use getComputedStyle to get all of the calculated style properties of an element.
var dom = document.querySelector("#foo");
console.log(getComputedStyle(dom).backgroundColor);
#foo {
background-color: red;
width: 10px;
height: 10px;
}
<div id="foo"></div>

Update Distance Between Elements

I have two elements, and one is moving towards the other. I am trying to get the new distance as it moves closer. Consider the code below:
<html>
<center>
<body onload = 'start()'>
<div class='field'>
<div id='bull'></div>
<div id='mount'></div>
</div>
<button id='one'>DO</button>
</body>
</center>
<style>
.field{
width: 440px;
height: 260px;
background: rgba(0, 0, 0, .2);
margin-top: 30px;
border: 1px solid #222;
border-radius: 10px;
}
#bull{
width: 15px;
height: 10px;
background: #000;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
position: absolute;
}
#mount{
width: 60px;
height: 30px;
background: rgba(20, 10, 45);
color: #fff;
border-radius: 4px;
margin-top: 210px;
}
</style>
<script type='text/javascript'>
function start() {
var ball = document.getElementById('bull');
var button = document.getElementById('one');
var mount = document.getElementById('mount');
button.addEventListener('click', go);
var x_pos = 0;
var y_pos = 0;
var bounce_point = 200;
var ball_dim = ball.getBoundingClientRect();
var ball_h_half = ball_dim.width / 2;
var ball_w_half = ball_dim.height / 2;
var mount_dim = mount.getBoundingClientRect();
var mount_h_half = mount_dim.width / 2;
var mount_w_half = mount_dim.height / 2;
function go() {
for(x_pos = 0; bounce_point > x_pos; x_pos++) {
ball.style.margin = x_pos + "px";
ball.style.transition = x_pos/2 + "s";
var dist = ((ball_h_half - mount_h_half)*(ball_w_half - mount_w_half)) + ((mount_h_half - ball_h_half)*(mount_w_half - ball_w_half));
console.log(dist);
if(dist < 3) {
console.log('One');
}
}
}
}
</script>
When bull reaches comes within 3px of mount, nothing happens... I've pretty much explained the issue as best as I can.
**
When bull reaches comes within 3px of mount, nothing happens... I've pretty much explained the issue as best as I can.**
Well i tried a little bit more, and your logic doens't seem to fit to what you want to do. First of all, you probably noticed your value in the log doesn't change.
It could have been because the values are retreived outside the loop, but not only (they actually have to be in the loop to be updated). You have 2 other problems: first, you are measuring the elements width and height, which don't take account of margin or other positioning. Your elements don't change size, so the value also won't. The other problem is actually the transition itself on the movement. Because of the delay, all your loop iterations are most probably done, and the margin already set to its final value when your "bull" effectively starts to move. It means that in the loop, you can't detect the position change, the element having not started to move yet. Using the value that was just set (margin) instead of detecting the real position of the element should show a progression for the value, but it makes harder to detect the collision because your 2 elements don't have the same positioning rules and you can't just compare the margins.
Here is a quick example that gets updated values (because the transition has been disabled, if you enable back, the problem comes again). You'll notice your calculation for the collision is wrong too. You can't just compare a distance between 2 corners for that, for a rectangle it's rather "has gone beyond left vertical edge AND has gone beyond top horizontal edge" (this of course takes only in account the top left corner, to be complete, it should also be added that it must not have reached the right or bottom edge yet).
Well, I can't propose you an all ready solution, but this addresses your code main issues:
<html>
<center>
<body onload = 'start()'>
<div class='field'>
<div id='bull'></div>
<div id='mount'></div>
</div>
<button id='one'>DO</button>
</body>
</center>
<style>
.field{
width: 440px;
height: 260px;
background: rgba(0, 0, 0, .2);
margin-top: 30px;
border: 1px solid #222;
border-radius: 10px;
}
#bull{
width: 15px;
height: 10px;
background: #000;
border-top-right-radius: 5px;
border-bottom-right-radius: 5px;
position: absolute;
}
#mount{
width: 60px;
height: 30px;
background: rgba(20, 10, 45);
color: #fff;
border-radius: 4px;
margin-top: 210px;
}
</style>
<script type='text/javascript'>
function start() {
var ball = document.getElementById('bull');
var button = document.getElementById('one');
var mount = document.getElementById('mount');
button.addEventListener('click', go);
var x_pos = 0;
var y_pos = 0;
var bounce_point = 200;
var ball_dim, ball_x, ball_y, mount_dim, mount_x, mount_y, diff_x, diff_y;
var stayInLoop = true;
//ball.style.transition = "0.4s"; //i don't know why you updated the transition time based on position, changed to a fixed value outside the loop because it's quicker for the example
function go() {
for(x_pos = 0; bounce_point > x_pos && stayInLoop; x_pos++) {
ball_dim = ball.getBoundingClientRect();
ball_y = ball_dim.top + 10; // +10 because we're considering the bottom edge of bull
ball_x = ball_dim.left + 15; // +15 because we're considering the right edge of bull
mount_dim = mount.getBoundingClientRect();
mount_y = mount_dim.top;
mount_x = mount_dim.left;
diff_x = mount_x - ball_x;
diff_y = mount_y - ball_y;
console.log(diff_x, diff_y);
ball.style.margin = x_pos + "px";
if(diff_x < 3 && diff_y < 3) {
console.log('One');
stayInLoop = false;
}
}
}
}
</script>
EDIT/SUGGESTION: i suggest looking at window.requestAnimationFrame() MDN doc here for a better control on animations

Categories