Custom cursor doesn't move - javascript

I'm trying to create a custom cursor for my website but it does not work well and I don't know what the problem is.
Here is the link to the code on Codepen
https://codepen.io/mahmoudkattan/pen/OJZXQow
const cursorTag = document.querySelector("div.cursor");
const cursor = cursorTag.querySelector("div");
let currentX = 0;
let currentY = 0;
let aimX = 0;
let aimY = 0;
let speed = 0.3;
const animate = function () {
currentX += (aimX - currentX) * speed;
currentY += (aimY - currentY) * speed;
cursor.style.left = currentX + "px";
cursor.style.top = currentY + "px";
requestAnimationFrame(animate);
};
animate();
document.addEventListener("mouseover", function (event) {
aimX = event.pageX;
aimY = event.pageY;
});
console.log(aimX);
div.cursor div {
z-index: 9999999;
position: fixed;
top: 300px;
left: 300px;
width: 45px;
height: 45px;
border: 1px solid var(--white);
border-radius: 50%;
pointer-events: none;
transform: translate(-50%, -50%);
}
<div class="cursor">
<div></div>
</div>
who can help with that?
Thanks

You want mousemove not mouseover

just change mouseover to mousemove
document.addEventListener("mousemove", function (event) {
aimX = event.pageX;
aimY = event.pageY;
});

Related

Only the first window is draggable

I created a code, where a window pops up. This window is draggable and resizable. I added a function in JavaScript, which adds two new windows when the first one is closed and adds more when the others are closed, but I also want them to be draggable as well.
I tried almost everything I know, but I don't seem to understand the issue.
const windowElement = document.querySelector("#window");
const header = document.querySelector("#header2");
const resizeContainer = document.querySelector("#resize-container");
let isDragging = false;
let currentX;
let currentY;
let xOffset = 0;
let yOffset = 0;
let isResizing = false;
let initialX;
let initialY;
let initialWidth;
let initialHeight;
let currentWidth;
let currentHeight;
const minimumWidth = 150;
const minimumHeight = 150;
header.addEventListener("mousedown", dragStart);
header.addEventListener("mouseup", dragEnd);
header.addEventListener("mousemove", drag);
resizeContainer.addEventListener("mousedown", resizeStart);
resizeContainer.addEventListener("mouseup", resizeEnd);
resizeContainer.addEventListener("mousemove", resize);
function dragStart(e) {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
isDragging = true;
}
function dragEnd(e) {
isDragging = false;
}
function drag(e) {
e.preventDefault();
if (isDragging) {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, windowElement);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
function resizeStart(e) {
initialX = e.clientX;
initialY = e.clientY;
initialWidth = windowElement.offsetWidth;
initialHeight = windowElement.offsetHeight;
isResizing = true;
}
function resizeEnd(e) {
isResizing = false;
}
function resize(e) {
if (isResizing) {
currentWidth = initialWidth + (e.clientX - initialX);
currentHeight = initialHeight + (e.clientY - initialY);
if (currentWidth >= minimumWidth) {
windowElement.style.width = currentWidth + "px";
}
if (currentHeight >= minimumHeight) {
windowElement.style.height = currentHeight + "px";
}
}
}
function closeWindow() {
const parentElement = document.querySelector("#parent");
const windowElement = document.querySelector("#window");
windowElement.style.display = "none";
setTimeout(() => {
const newWindow1 = windowElement.cloneNode(true);
const newWindow2 = windowElement.cloneNode(true);
const xPos1 = Math.floor(Math.random() * (parentElement.offsetWidth - newWindow1.offsetWidth));
const yPos1 = Math.floor(Math.random() * (parentElement.offsetHeight - newWindow1.offsetHeight));
const xPos2 = Math.floor(Math.random() * (parentElement.offsetWidth - newWindow2.offsetWidth));
const yPos2 = Math.floor(Math.random() * (parentElement.offsetHeight - newWindow2.offsetHeight));
newWindow1.style.display = "";
newWindow2.style.display = "";
setTranslate(xPos1, yPos1, newWindow1);
setTranslate(xPos2, yPos2, newWindow2);
parentElement.appendChild(newWindow1);
parentElement.appendChild(newWindow2);
}, 500);
}
function createWindow() {
const parentElement = document.querySelector("#parent");
const windowElement = document.createElement("div");
let isDragging = false;
let currentX;
let currentY;
let initialX;
let initialY;
let xOffset = 0;
let yOffset = 0;
function dragStart(e) {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
isDragging = true;
}
function dragEnd(e) {
isDragging = false;
}
function drag(e) {
if (isDragging) {
e.preventDefault();
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, this.parentNode);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
windowElement.classList.add("old-computer-window");
windowElement.style.left = Math.floor(Math.random() * (parentElement.offsetWidth - 300)) + "px";
windowElement.style.top = Math.floor(Math.random() * (parentElement.offsetHeight - 300)) + "px";
windowElement.setAttribute("data-aos", "zoom-in");
windowElement.setAttribute("data-aos-delay", "300");
const header = document.createElement("div");
header.classList.add("header2");
header.innerHTML = '<p>DANIEL.JPG</p><div class="close" onclick="closeWindow(this)">✕</div>';
const imageContainer = document.createElement("div");
imageContainer.classList.add("image-container");
const resizeContainer = document.createElement("div");
resizeContainer.classList.add("resize-container");
windowElement.appendChild(header);
windowElement.appendChild(imageContainer);
windowElement.appendChild(resizeContainer);
parentElement.appendChild(windowElement);
header.addEventListener("mousedown", dragStart);
header.addEventListener("mouseup", dragEnd);
header.addEventListener("mousemove", drag);
resizeContainer.addEventListener("mousedown", resizeStart);
resizeContainer.addEventListener("mouseup", resizeEnd);
resizeContainer.addEventListener("mousemove", resize);
}
#computer-window {
width: 100%;
height: 300px;
background-color: #ddd;
border-style: solid;
border-width: 2px;
border-left-color: white;
border-top-color: white;
border-bottom-color: darkred;
border-right-color: darkred;
}
#header2 {
background-color: black;
color: #fff;
padding: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
#title {
font-size: 20px;
font-weight: bold;
}
#close-btn {
border-style: solid;
border-width: 2px;
border-left-color: white;
border-top-color: white;
border-bottom-color: darkred;
border-right-color: darkred;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
}
#parent {
position: relative;
width: 800px;
height: 600px;
border: orange;
}
#window {
position: absolute;
width: 100%;
max-height: 1080px;
background-color: white;
border-style: solid;
border-width: 2px;
border-left-color: #191919;
border-top-color: #191919;
border-bottom-color: darkred;
border-right-color: darkred;
user-select: none;
overflow: hidden;
<div data-aos="zoom-in" data-aos-delay="300" id="parent">
<div class="old-computer-window" id="window">
<div class="header2" id="header2">
<p>DANIEL.JPG</p>
<div class="close" id="close" onclick="closeWindow()">✕</div>
</div>
<div class="image-container"></div>
<div class="resize-container" id="resize-container"></div>
</div>
</div>

Clearinterval method is unable to clear Rotation javascript animation

I am new to JS and i am trying to move object from left to right while spinning clockwise, here i applied setinterval for movement animation from left to right and also for rotation. I am able to clearinterval Movement from left to right but unable to clearinterval my Rotation i don't know why please if you can take a look
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
e.style.left = (eLeftPos + s) + 'px';
function rot() {
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
}
var rotID = setInterval(rot, 1000)
var leftPos = (eLeftPos + s) >= 1000
if ((eLeftPos + s) >= 1000) {
clearInterval(rotID)
console.log(rotID)
}
if ((eLeftPos + s) >= 1000) {
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>
You're unable to clear the interval from the rotation, because you start a new setInterval every time the first (movement) interval executes. You'll have a new rotation interval every 1000ms. Why not just move and rotate within the same setInterval callback and then theres only 1 to cancel:
window.topPos = '';
var e = document.getElementById("aDiv");
var s = 1;
var rotate = false;
var degrees = 0;
function myInterval() {
var eLeftPos = e.offsetLeft;
var leftPos = (eLeftPos + s); // new left pos
e.style.left = leftPos + 'px';
degrees++;
e.style.transform = 'rotate(' + degrees + 'deg)';
if (leftPos >= 100) { // made 100 just to show the effect quicker
clearInterval(internal)
}
}
var internal = setInterval(myInterval, 100);
#aDiv {
background: black;
width: 80px;
height: 80px;
position: relative;
}
#aDiv1 {
background: red;
width: 80px;
height: 80px;
position: absolute;
}
<div id="aDiv"></div>
<button>Stop</button>

sin and cos animations on a curved line with javascript and CSS

I am trying to use sin and cos to animate a CSS image to move on this shape. Can not make the CSS image to move on that curved bezier line.
Can someone assist on how to use sin or cos in so, if a CSS object added, it would move smoothly along such a line?
Here is the code that I tried to make the yellow circle to move on that line with sin and cos math in javascript.
Thanks
var field = document.getElementById("field");
var ball = document.getElementById("ball");
var ball2 = document.getElementById("ball2");
var maxX = field.clientWidth - ball.offsetWidth;
var maxY = field.clientHeight - ball.offsetHeight;
var duration = 5; // seconds
var gridSize = 50; // pixels
var start = null;
function step(timestamp) {
var progress, x, y, y2;
if (start === null)
start = timestamp;
progress = (timestamp - start) / duration / 1000; // percent
x = progress * maxX / gridSize; // x = ƒ(t)
y = 2 * Math.sin(x); // y = ƒ(x)
y2 = 2 * Math.cos(x);
ball.style.left = ball2.style.left = Math.min(maxX, gridSize * x)
+ "px";
ball.style.bottom = maxY / 2 + (gridSize * y) + "px";
ball2.style.bottom = maxY / 2 + (gridSize * y2) + "px";
if (progress >= 1)
start = null; // reset to start position
requestAnimationFrame(step);
}
requestAnimationFrame(step);
#field {
position: absolute;
height: 300px;
width: 300px;
z-index: 50;
top: 20px;
left: 20px;
}
#ball {
position: absolute;
left: 0;
bottom: 50%;
width: 40px;
background: yellow;
z-index: 5;
height: 40px;
border-radius: 200px;
}
#ball2 {
position: absolute;
left: 0;
bottom: 50%;
width: 20px;
height: 20px;
/*background: silver;*/
border-radius: 100px;
}
<div id="field">
<div id="ball"></div>
<div id="ball2"></div>
</div>
requestAnimationFrame calls the given function exactly ONCE
to animate, you need to call requestAnimationFrame within that given function, usually calling the function itself (though more complex animations may call something else, it doesn't matter)
The main point being, you need to call requestAnimationFrame for each frame you want to animate
var field = document.getElementById("field");
var ball = document.getElementById("ball");
var ball2 = document.getElementById("ball2");
var maxX = field.clientWidth - ball.offsetWidth;
var maxY = field.clientHeight - ball.offsetHeight;
var duration = 5; // seconds
var gridSize = 40; // pixels
var start = null;
function step(timestamp) {
var progress, x, y, y2;
if (start === null)
start = timestamp;
progress = (timestamp - start) / duration / 1000; // percent
x = progress * maxX / gridSize; // x = ƒ(t)
y = -2 * Math.cos(x); // y = ƒ(x)
y2 = 2 * Math.cos(x);
ball.style.left = ball2.style.left = Math.min(maxX, gridSize * x) +
"px";
ball.style.bottom = maxY / 2 + (gridSize * y) + "px";
ball2.style.bottom = maxY / 2 + (gridSize * y2) + "px";
if (progress >= 1)
start = null; // reset to start position
requestAnimationFrame(step);
}
requestAnimationFrame(step);
#field {
position: absolute;
height: 300px;
width: 300px;
z-index: 50;
top: 20px;
left: 20px;
}
#ball {
position: absolute;
left: 0;
bottom: 50%;
width: 40px;
background: yellow;
height: 40px;
border-radius: 200px;
}
#ball2 {
position: absolute;
left: 0;
bottom: 50%;
width: 20px;
height: 20px;
background: silver;
border-radius: 100px;
}
<div id="field">
<div id="ball"></div>
<div id="ball2"></div>
</div>

Javascript Easing no working in Firefox

The below HTML and Javascript has an easing function applied to a background. It works fine in Chrome, Safari, and even IE, but not firefox?
anyone out there know why it wont work in FF?
var element = "ele";
var ease_against = true;
window.onload = function() {
var target = {
x: 0,
y: 0
};
var position = {
x: target.x,
y: target.y
},
ease = 0.2;
document.getElementById(element).addEventListener("mousemove", function(event) {
target.x = event.clientX / 5;
target.y = event.clientY / 5;
});
update();
function update() {
var vx = ease_against ? (((target.x - target.x - target.x) - position.x) * ease) : ((target.x - position.x) * ease);
var vy = ease_against ? (((target.y - target.y - target.y) - position.y) * ease) : ((target.y - position.y) * ease);
position.x += vx;
position.y += vy;
document.getElementById(element).style.backgroundPositionY = position.y + "px";
document.getElementById(element).style.backgroundPositionX = position.x + "px";
requestAnimationFrame(update);
}
};
html,
body {
margin: 0;
width: 100%;
height: 100%;
padding: 0;
}
#ele {
background: url('hex.jpg') repeat;
width: 400px;
height: 400px;
margin-left: auto;
margin-right: auto;
border-top: 1px solid black;
border-bottom: 1px solid black;
border-radius: 50%;
overflow: hidden;
}
<div id="ele">
</div>
It's not the easing that causes your problem.
Firefox doesn't support backgroundPositionX, but it does support background position
For example you can do:
myElement.style.backgroundPosition = position.x + "px "+position.y + "px";

Drag an HTML box and make another box follow it with JavaScript

I am trying to create something like drag a box (Hello World) to any location, and the second box (Follow World) will follow slowly.
In the code below, the drag box is fine, but the follow box will not follow properly. Also, the drag box cannot drop.
function startDrag(e) {
// determine event object
if (!e) {
var e = window.event;
}
// IE uses srcElement, others use target
var targ = e.target ? e.target : e.srcElement;
if (targ.className != 'dragme') {
return
};
// calculate event X, Y coordinates
offsetX = e.clientX;
offsetY = e.clientY;
// assign default values for top and left properties
if (!targ.style.left) {
targ.style.left = '0px'
};
if (!targ.style.top) {
targ.style.top = '0px'
};
// calculate integer values for top and left
// properties
coordX = parseInt(targ.style.left);
coordY = parseInt(targ.style.top);
drag = true;
// move div element
document.onmousemove = dragDiv;
return false;
}
function dragDiv(e) {
if (!drag) {
return
};
if (!e) {
var e = window.event
};
var targ = e.target ? e.target : e.srcElement;
// move div element
targ.style.left = coordX + e.clientX - offsetX + 'px';
targ.style.top = coordY + e.clientY - offsetY + 'px';
return false;
}
function stopDrag() {
timer();
drag = false;
}
window.onload = function() {
document.onmousedown = startDrag;
document.onmouseup = stopDrag;
}
function disp() {
var step = 1;
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
var ty = document.getElementById('draggable').offsetTop;
var ty = document.getElementById('draggable').offsetLeft;
if (y < ty) {
y = y + step;
document.getElementById('followme').style.top = y + "px"; // vertical movment
} else {
if (x < tx) {
x = x + step;
document.getElementById('followme').style.left = x + "px"; // horizontal movment
}
}
}
function timer() {
disp();
var y = document.getElementById('followme').offsetTop;
var x = document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML = "X: " + tx + " Y : " + ty
my_time = setTimeout('timer()', 10);
}
.dragme {
position: relative;
width: 60px;
height: 80px;
cursor: move;
}
.followme {
position: relative;
width: 60px;
height: 80px;
}
#draggable {
background-color: #ccc;
border: 1px solid #000;
}
#followme {
background-color: #ccc;
border: 1px solid #000;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Drag and drop</title>
</head>
<body>
<div id='msg'></div>
<div id="draggable" class="dragme">"Hello World!"</div>
<div id="followme" class="followme">"Follow World!"</div>
Fix yours disp and timer functions to this:
function disp()
{
var step = 1;
// in dragDiv() you modifying style.left/style.top properties, not offsetTop/offsetLeft
var x = parseInt(document.getElementById('followme').style.left) || 0;
var y = parseInt(document.getElementById('followme').style.top) || 0;
var tx = parseInt(document.getElementById('draggable').style.left) || 0;
var ty = parseInt(document.getElementById('draggable').style.top) || 0;
// properly calculate offset
var dx = ((dx = tx - x) == 0) ? 0 : Math.abs(dx) / dx;
var dy = ((dy = ty - y) == 0) ? 0 : Math.abs(dy) / dy;
document.getElementById('followme').style.left = (x + dx * step) + "px"; // horisontal movment
document.getElementById('followme').style.top = (y + dy * step) + "px"; // vertical movment
}
function timer()
{
disp();
var y=document.getElementById('followme').offsetTop;
var x=document.getElementById('followme').offsetLeft;
document.getElementById("msg").innerHTML="X: " + x + " Y : " + y; // typo was here
my_time = setTimeout(function () {
clearTimeout(my_time); // need to clear timeout or it'll be adding each time 'Hello world' clicked
timer();
},10);
}
In the following snippet, the pink box is draggable and the blue box follows it around. You can change pixelsPerSecond to adjust the speed of movement.
function message(s) {
document.getElementById('messageContainer').innerHTML = s;
}
window.onload = function () {
var pixelsPerSecond = 80,
drag = document.getElementById('drag'),
follow = document.getElementById('follow'),
wrapper = document.getElementById('wrapper'),
messageContainer = document.getElementById('messageContainer'),
leftMax,
topMax;
function setBoundaries() {
leftMax = wrapper.offsetWidth - drag.offsetWidth;
topMax = wrapper.offsetHeight - drag.offsetHeight;
drag.style.left = Math.min(drag.offsetLeft, leftMax) + 'px';
drag.style.top = Math.min(drag.offsetTop, topMax) + 'px';
}
setBoundaries();
window.onresize = setBoundaries;
[drag, follow, messageContainer].forEach(function (element) {
element.className += ' unselectable';
element.ondragstart = element.onselectstart = function (event) {
event.preventDefault();
};
});
var start = Date.now();
drag.onmousedown = function (event) {
event = event || window.event;
var x0 = event.pageX || event.clientX,
y0 = event.pageY || event.clientY,
left0 = drag.offsetLeft,
top0 = drag.offsetTop;
window.onmousemove = function (event) {
var x = event.pageX || event.clientX,
y = event.pageY || event.clientY;
drag.style.left = Math.max(0, Math.min(left0 + x - x0, leftMax)) + 'px';
drag.style.top = Math.max(0, Math.min(top0 + y - y0, topMax)) + 'px';
};
window.onmouseup = function () {
window.onmousemove = window.onmouseup = undefined;
};
};
follow.x = follow.offsetLeft;
follow.y = follow.offsetTop;
function update() {
var elapsed = Date.now() - start;
if (elapsed === 0) {
window.requestAnimationFrame(update);
return;
}
var x1 = drag.offsetLeft,
y1 = drag.offsetTop + (drag.offsetTop + drag.offsetHeight <= topMax ?
drag.offsetHeight : -drag.offsetHeight),
x0 = follow.x,
y0 = follow.y,
dx = x1 - x0,
dy = y1 - y0,
distance = Math.sqrt(dx*dx + dy*dy),
angle = Math.atan2(dy, dx),
dd = Math.min(distance, pixelsPerSecond * elapsed / 1000);
message('x: ' + x1 + ', y: ' + y1);
follow.x += Math.cos(angle) * dd;
follow.style.left = follow.x + 'px';
follow.y += Math.sin(angle) * dd;
follow.style.top = follow.y + 'px';
start = Date.now();
window.requestAnimationFrame(update);
}
window.requestAnimationFrame(update);
};
#wrapper {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #eee;
font-family: sans-serif;
text-align: center;
}
.unselectable {
-webkit-user-select: none;
-khtml-user-drag: none;
-khtml-user-select: none;
-moz-user-select: none;
-moz-user-select: -moz-none;
-ms-user-select: none;
user-select: none;
}
#messageContainer {
position: absolute;
left: 80px;
top: 50px;
font-size: 36px;
color: #aaa;
cursor: default;
}
.box {
position: absolute;
width: 60px;
height: 80px;
}
.label {
margin: 30px auto;
font-size: 14px;
}
#drag {
left: 100px;
top: 120px;
background: #f0dddb;
border: 2px solid #deb7bb;
cursor: move;
}
#follow {
left: 0;
top: 0;
background-color: #ddebf3;
border: 2px solid #bfd5e1;
cursor: default;
}
<div id="wrapper">
<div id="messageContainer"></div>
<div class="box" id="follow"> <div class="label">it follows</div> </div>
<div class="box" id="drag"> <div class="label">drag me</div> </div>

Categories

Resources