Gradient follows mouse but doesn't catch up - javascript

I've put together a simple jQuery script to create a radial gradient that follows the mouse with a delay, but since it's in a mousemove function, when the mouse stops moving the gradient doesn't catch up. Is there a simple way to make the gradient catch up with the mouse when the mouse stops without writing a function that's constantly running?
var xPos = 0;
var yPos = 0;
var dX = 0;
var dY = 0;
var repeater;
$(document).mousemove(function(event) {
windowWidth = $(window).width();
windowHeight = $(window).height();
mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);
dX = mouseXpercentage - xPos;
dY = mouseYpercentage - yPos;
xPos += (dX / 50);
yPos += (dY / 50);
$('.rgradient').css('background', 'radial-gradient(at ' + xPos + '% ' + yPos + '%, #e6e6e6, #1e1e1e)');
});
.rgradient {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #1e1e1e;
background: radial-gradient( at center, #e6e6e6 #1e1e1e);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rgradient"></div>

You can use requestAnimationFrame(), as it only runs once for each frame:
var xPos = 0;
var yPos = 0;
var dX = 0;
var dY = 0;
var mouseRaf = null;
var gradMoveRaf = null;
$(document).mousemove(function(event) {
if (!mouseRaf) {
mouseRaf = requestAnimationFrame(function() {
windowWidth = $(window).width();
windowHeight = $(window).height();
mouseXpercentage = Math.round(event.pageX / windowWidth * 100);
mouseYpercentage = Math.round(event.pageY / windowHeight * 100);
dX = mouseXpercentage - xPos;
dY = mouseYpercentage - yPos;
mouseRaf = null;
});
}
if (!gradMoveRaf) {
gradMoveRaf = requestAnimationFrame(gradMove);
}
});
function gradMove() {
xPos += (dX / 50);
yPos += (dY / 50);
$('.rgradient').css('background', 'radial-gradient(at ' + xPos + '% ' + yPos + '%, #e6e6e6, #1e1e1e)');
var absX = Math.abs(mouseXpercentage - xPos);
var absY = Math.abs(mouseYpercentage - yPos);
if (absX < 1 && absY < 1) {
gradMoveRaf = null;
console.log("stop");
} else {
gradMoveRaf = requestAnimationFrame(gradMove);
console.log("repeat");
}
}
.rgradient {
position: fixed;
top: 0px;
left: 0px;
height: 100%;
width: 100%;
background: #1e1e1e;
background: radial-gradient(at center, #e6e6e6 #1e1e1e);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rgradient"></div>

Related

Mobile accelerometer - Slow div on rotate

I'm using the following code to move a ball around the screen when my mobile phone is rotated:
HTML
<html>
<head>
<meta charset="utf-8">
<title>Gyro_Ball</title>
<link rel="stylesheet" href="css/style.css">
<script src="js/main.js"></script>
</head>
<body onload="init()">
<div id="ball"></div>
</body>
</html>
SCRIPT
if ( !window.requestAnimationFrame ) {
window.requestAnimationFrame = ( function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element ) {
window.setTimeout( callback, 1000 / 60 );
};
} )();
}
var ball;
var w;
var h;
function init()
{
ball = document.getElementById("ball");
w = window.innerWidth;
h = window.innerHeight;
ball.style.left = (w/2)-50+"px";
ball.style.top = (h/2)-50+"px";
ball.velocity = {x:0,y:0}
ball.position = {x:0,y:0}
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function(event)
{
ball.velocity.y = Math.round(event.beta);
ball.velocity.x = Math.round(event.gamma);
}
)
};
update();
}
function update()
{
ball.position.x += ball.velocity.x;
ball.position.y += ball.velocity.y;
if(ball.position.x > (w-100) && ball.velocity.x > 0)
{
ball.position.x = w-100;
}
if(ball.position.x < 0 && ball.velocity.x < 0)
{
ball.position.x = 0;
}
if(ball.position.y > (h-100) && ball.velocity.y > 0)
{
ball.position.y = h-100;
}
if(ball.position.y < 0 && ball.velocity.y < 0)
{
ball.position.y = 0;
}
ball.style.top = ball.position.y + "px"
ball.style.left = ball.position.x + "px"
requestAnimationFrame(update);//KEEP ANIMATING
}
CSS
body {
padding:0;
margin:0;
background-color: #32c9d6;
}
#ball
{
-webkit-transition: all;
transition: all;
position:absolute;
width:100px;
height:100px;
border-radius: 50%;
background: white;
}
It works great! BUT I need to slow the ball down when I rotate my mobile....any ideas?
HERE IS A DEMO (Use Your mobile to view it):
http://inkfood.github.io/Gyro_Ball2/
JSFIDDLE (Use Your mobile to view it):
https://jsfiddle.net/qq74w6a3/6/
I just need to slow that ball down when tilting left to right so it doesn't zoom across so fast...there must be a delay or acceleration or FPS I can use to slow it down?
I tried getting this to work on mobile, but I couldn't. But I did add a mouse event which uses the mouse delta to slow the ball.
I calculate how far the mouse is away from the ball center and then use that percentage to adjust the velocity. I think you could use this to find how far the ball center is from the oriented side. i.e. the bottom.
Run the embedded script and move your mouse around. The ball should slow as it gets closer to the mouse position.
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
}
var ball;
var dbg;
var w;
var h;
var my = 0;
var mx = 0;
function update() {
ball.position.x += ball.velocity.x;
ball.position.y += ball.velocity.y;
if (ball.position.x > (w - 100) && ball.velocity.x > 0) {
ball.position.x = w - 100;
}
if (ball.position.x < 0 && ball.velocity.x < 0) {
ball.position.x = 0;
}
if (ball.position.y > (h - 100) && ball.velocity.y > 0) {
ball.position.y = h - 100;
}
if (ball.position.y < 0 && ball.velocity.y < 0) {
ball.position.y = 0;
}
ball.style.top = ball.position.y + "px";
ball.style.left = ball.position.x + "px";
requestAnimationFrame(update); //KEEP ANIMATING
}
function init() {
ball = document.getElementById("ball");
dbg = document.getElementById("debug");
w = window.innerWidth;
h = window.innerHeight;
ball.style.left = (w / 2) - 50 + "px";
ball.style.top = (h / 2) - 50 + "px";
ball.velocity = {
x: 0,
y: 0
};
ball.position = {
x: 0,
y: 0
};
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", function(event) {
ball.velocity.y = Math.round(event.beta);
ball.velocity.x = Math.round(event.gamma);
});
} else {
window.addEventListener("mousemove", function(event) {
my = event.clientY;
mx = event.clientX;
});
window.setInterval(function() {
var wy = window.outerHeight;
var wx = window.outerWidth;
var bcy = ball.position.y + 50; //ball center Y
var bcx = ball.position.x + 50; // ball center X
var dy = Math.round(((my - bcy) * 100 / wy) * 10000) / 10000;
var dx = Math.round(((mx - bcx) * 100 / wx) * 10000) / 10000;
ball.velocity.y = dy;
ball.velocity.x = dx;
dbg.innerHTML = 'deltaY:' + dy + ' deltaX:' + dx;
}, 100);
}
update();
}
init();
#ball {
-webkit-transition: all;
transition: all;
position: absolute;
width: 100px;
height: 100px;
border-radius: 50%;
background: red;
}
#debug {
position: absolute;
top: 5px;
left: 5px;
display: inline-block;
width: auto;
height: auto;
padding: 5px 10px;
z-index: 2;
color: rgb(255, 255, 255);
background: rgba(0, 0, 0, 0.75);
font-family: monospace;
font-size: 11px;
}
<div id="ball"></div>
<div id="debug">x:0 y:0</div>

Making div appear from off-screen

I'm doing this assignment where I have to use pure javascript to make a div appear from the side of the screen without having the browser expand. This is what I have so far:
function moveImg() {
var div = document.getElementsByTagName('div')[0];
var pos = 500;
var id = setInterval(Move, 500);
function Move() {
if (pos <= 0) {
clearInterval(id);
} else {
pos++;
div.style.right = pos + 'px';
div.style.top = pos + 'px';
}
}
}
moveImg()
div {
width: 50px;
height: 50px;
background: tomato;
}
<div></div>
I'd use transform generally.
I've done some maths too, I've commented to code but feel free to ask if there's anything you need help understanding.
function moveImg() {
var div = document.getElementsByTagName('div')[0];
var posX = document.body.clientWidth - div.offsetWidth; // start position for X
var posY = document.body.clientHeight - div.offsetHeight; // start position for Y
var tarX = posX / 2; // end position for X
var tarY = posY / 2; // end position for Y
var time = 5; // how many seconds should the animation take
var fps = 60; // frames per second, heigher is smoother but requires more power
var stepX = ((posX - tarX) / (time * fps)); // how far X should move each frame
var stepY = ((posY - tarY) / (time * fps)); // how far Y should move each frame
var id = setInterval(Move, (1000 / fps));
div.style.transform = "translate(" + posX + "px, " + posY + "px)";
div.style.opacity = "1";
function Move() {
if (posX <= tarX && posY <= tarY) {
clearInterval(id);
} else {
posX -= stepX;
posY -= stepY;
div.style.transform = "translate(" + posX + "px, " + posY + "px)";
}
}
}
moveImg();
body {
margin: 0;
width: 100vw;
height: 100vh;
}
div {
display: inline-block;
color: white;
padding: 15px 30px;
background: tomato;
opacity: 0;
}
<div>Example!</div>
Like what was said in the comments, you don't say in what direction you want your div to move, nor from which position it should start.
I've set the starting position of top:100, left:100 and reducing the top and left values by 1px each second:
function moveImg() {
var div = document.getElementsByTagName('div')[0];
var pos = 100;
var id = setInterval(Move, 500);
function Move() {
if (pos <= 0) {
clearInterval(id);
} else {
pos--;
div.style.left = pos + 'px';
div.style.top = pos + 'px';
}
}
}
moveImg()
div {
width: 50px;
height: 50px;
background: tomato;
position: relative;
top: 100px;
left: 100px;
}
<div></div>

Ball animation using javascript

I did a animation using javascript. Using single ball shape goes top of the page. Anybody would help how to create multiple balls like clone.. I just want the following tasks..
Animation with multiple balls (Bottom to top)
Each ball position (Left position only) is random.
Infinite process.
Is it possible to achieve through javascript. Thanks in advance :)
.circle{
width: 50px;
height: 50px;
border-radius: 30px;
position: absolute;
bottom: -60px;
left: 2px;
transition: 0.1s;
}
body{
overflow: hidden;
position: relative;
background: violet
}
#box{
width: 100%;
height: 100%;
}
<body>
<div id="box"></div>
<script type="text/javascript">
var colors = ['red', 'yellow', 'blue', 'green', 'brown', 'violet'];
var windowHeight = 0;
var parendElement;
window.onload = function () {
parendElement = document.getElementById("box");
windowHeight = window.innerHeight;
document.body.style.height = windowHeight + "px";
console.log(document.body.style.height);
generateBall();
};
function generateBall() {
var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
var para = document.createElement("p");
para.setAttribute("class", 'circle');
para.style.background = colors[Math.floor(Math.random() * colors.length)];
para.style.left = leftPos + "px";
parendElement.appendChild(para);
var btmPos = 0;
var animationInterval = setInterval(function () {
if (btmPos < windowHeight) {
btmPos += 5;
} else {
console.log("yes");
clearInterval(animationInterval);
parendElement.removeChild(para);
}
para.style.bottom = btmPos + "px";
para.style.left = leftPos + "px";
}, 100);
}
</script>
</body>
This might help you..
var canvas = {
element: document.getElementById('canvas'),
width: 600,
height: 400,
initialize: function () {
this.element.style.width = this.width + 'px';
this.element.style.height = this.height + 'px';
document.body.appendChild(this.element);
}
};
var Ball = {
create: function (color, dx, dy) {
var newBall = Object.create(this);
newBall.dx = dx;
newBall.dy = dy;
newBall.width = 40;
newBall.height = 40;
newBall.element = document.createElement('div');
newBall.element.style.backgroundColor = color;
newBall.element.style.width = newBall.width + 'px';
newBall.element.style.height = newBall.height + 'px';
newBall.element.className += ' ball';
newBall.width = parseInt(newBall.element.style.width);
newBall.height = parseInt(newBall.element.style.height);
canvas.element.appendChild(newBall.element);
return newBall;
},
moveTo: function (x, y) {
this.element.style.left = x + 'px';
this.element.style.top = y + 'px';
},
changeDirectionIfNecessary: function (x, y) {
if (x < 0 || x > canvas.width - this.width) {
this.dx = -this.dx;
}
if (y < 0 || y > canvas.height - this.height) {
this.dy = -this.dy;
}
},
draw: function (x, y) {
this.moveTo(x, y);
var ball = this;
setTimeout(function () {
ball.changeDirectionIfNecessary(x, y);
ball.draw(x + ball.dx, y + ball.dy);
}, 1000 / 60);
}
};
canvas.initialize();
var ball1 = Ball.create("blue", 4, 3);
var ball2 = Ball.create("red", 1, 5);
var ball3 = Ball.create("green", 2, 2);
ball1.draw(70, 0);
ball2.draw(20, 200);
ball3.draw(300, 330);
body {
text-align: center;
}
#canvas {
position: relative;
background-color: #ccddcc;
margin: 1em auto;
}
.ball {
background-color: black;
position: absolute;
display: inline-block;
border-radius: 50%;
}
<h1>Bouncing Balls</h1>
<p>These bouncing balls are made with completely raw JavaScript,
just with divs. We don't use jQuery. We don't use canvas.</p>
<div id="canvas"></div>
Just add this code
var interval = setInterval(function () {
generateBall();
}, 1000);
into your window.onload(). It works :) ..
.circle{
width: 50px;
height: 50px;
border-radius: 30px;
position: absolute;
bottom: -60px;
left: 2px;
transition: 0.1s;
}
body{
overflow: hidden;
position: relative;
background: violet
}
#box{
width: 100%;
height: 100%;
}
<body>
<div id="box"></div>
<script type="text/javascript">
var colors = ['red', 'yellow', 'blue', 'green', 'brown', 'violet'];
var windowHeight = 0;
var parendElement;
window.onload = function () {
parendElement = document.getElementById("box");
windowHeight = window.innerHeight;
document.body.style.height = windowHeight + "px";
console.log(document.body.style.height);
generateBall();
//Creates ball for every 1 second interval
var interval = setInterval(function () {
generateBall();
}, 1000);
};
function generateBall() {
var leftPos = Math.floor((Math.random() * window.innerWidth) - 30);
var para = document.createElement("p");
para.setAttribute("class", 'circle');
para.style.background = colors[Math.floor(Math.random() * colors.length)];
para.style.left = leftPos + "px";
parendElement.appendChild(para);
var btmPos = 0;
var animationInterval = setInterval(function () {
if (btmPos < windowHeight) {
btmPos += 5;
} else {
console.log("yes");
clearInterval(animationInterval);
parendElement.removeChild(para);
}
para.style.bottom = btmPos + "px";
para.style.left = leftPos + "px";
}, 100);
}
</script>
</body>

Move a coordinate along an angled line using mouse movement

Please run the code snippet below - you will see an angled line derived from the corners of a box. Given mouse movement, I would like to move the marker along this line - where either:
movement in x will move along the line, and additional movement in y will accelerate
movement in x will move along the line and you can get from start to finish with it (whatever is simplest)
So far I haven't got anywhere but I'll update if I do and many thanks for any help.
PS doesn't really matter if it doesn't move exactly along the line - it's the algorithm to move along an angle I'm interested in.
Fiddle: http://jsfiddle.net/ngr3dbhx/3/
var boxEl = document.getElementById('box');
var lineEl = document.getElementById('line');
var markerEl = document.getElementById('marker');
var rad, deg;
// Draw an angled line for demonstration purposes.
function getElementOffset (el) {
var rect = el.getBoundingClientRect();
var docEl = document.documentElement;
var rectTop = rect.top + window.pageYOffset - docEl.clientTop;
var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;
return {
top: rectTop,
left: rectLeft
};
}
function calcAndDrawAngle () {
var boxOffset = getElementOffset(boxEl);
var x1 = boxOffset.left;
var y1 = boxOffset.top;
var x2 = boxOffset.left + boxEl.offsetWidth;
var y2 = boxOffset.top + boxEl.offsetHeight;
var deltaX = x2 - x1;
var deltaY = y2 - y1;
rad = Math.atan2(deltaY, deltaX);
deg = rad * (180 / Math.PI);
lineEl.style.transform = 'rotate(' + deg + 'deg) translate(-50%, 0)';
}
// On mouse move I want to move the marker along the anged line..
// Do something with rad or deg?
document.addEventListener('mousemove', function (e) {
markerEl.style.top = e.clientY + 'px';
markerEl.style.left = e.clientX + 'px';
});
calcAndDrawAngle();
window.addEventListener('resize', calcAndDrawAngle);
html,
body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#box {
position: absolute;
top: 20%;
left: 30%;
width: 35%;
height: 30%;
border: 1px solid #999;
}
#line {
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
height: 1px;
width: 9999em;
background-color: black;
}
#marker {
position: absolute;
width: 8px;
height: 8px;
background-color: red;
}
<div id="box">
<div id="line"></div>
</div>
<div id="marker"></div>
you mean this?
https://jsfiddle.net/2q1nLh3q/1/
The formula is basic mathematics:
y = k * x + d
Where k is deltaY / deltaX and d is the point where the line crosses the y axis.
So your function could look like this:
document.addEventListener('mousemove', function (e) {
window.requestAnimationFrame(function() {
var boxOffset = getElementOffset(boxEl);
var k = boxEl.offsetHeight / boxEl.offsetWidth;
var d = boxOffset.top - boxOffset.left * k;
var mouseY = k * e.clientX + d;
markerEl.style.top = mouseY + 'px';
markerEl.style.left = e.clientX + 'px';
});
});
Using fairly simple math, calculate y for any x within limited range (subtracted 4 to place rectangle at center):
//var canvas = document.getElementById('canvas');
var boxEl = document.getElementById('box');
var lineEl = document.getElementById('line');
var markerEl = document.getElementById('marker');
var rad, deg;
var coords;
// Draw an angled line for demonstration purposes.
function getElementOffset (el) {
var rect = el.getBoundingClientRect();
var docEl = document.documentElement;
var rectTop = rect.top + window.pageYOffset - docEl.clientTop;
var rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;
return {
top: rectTop,
left: rectLeft
};
}
function calcAndDrawAngle () {
var boxOffset = getElementOffset(boxEl);
var x1 = boxOffset.left;
var y1 = boxOffset.top;
var x2 = boxOffset.left + boxEl.offsetWidth;
var y2 = boxOffset.top + boxEl.offsetHeight;
coords = [{x:x1,y:y2},{x:x2,y:y1}];
var deltaX = x2 - x1;
var deltaY = y2 - y1;
rad = Math.atan2(deltaY, deltaX);
deg = rad * (180 / Math.PI);
lineEl.style.transform = 'rotate(' + deg + 'deg) translate(-50%, 0)';
}
// On mouse move I want to move the marker along the anged line..
// Do something with rad or deg?
document.addEventListener('mousemove', function (e) {
var x = Math.min(Math.max(e.clientX, coords[0].x), coords[1].x) - 4;
var y = coords[0].y + ((coords[1].y - coords[0].y) * (coords[1].x - x) / (coords[1].x - coords[0].x));
markerEl.style.top = y + 'px';
markerEl.style.left = x + 'px';
});
calcAndDrawAngle();
window.addEventListener('resize', calcAndDrawAngle);
html,
body {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
#box {
position: absolute;
top: 20%;
left: 30%;
width: 35%;
height: 30%;
border: 1px solid #999;
}
#line {
position: absolute;
top: 0;
left: 0;
transform-origin: top left;
height: 1px;
width: 9999em;
background-color: black;
}
#marker {
position: absolute;
width: 8px;
height: 8px;
background-color: red;
}
<div id="box">
<div id="line"></div>
</div>
<div id="marker"></div>

Placing interactive box on top of the canvas on mouseleave

I'm trying to make a box follow the cursor on mousemove. However, it should stop following the mouse if
the user clicks the box
the user's mouse leaves the surrounding div
Here's what the current setup looks like:
$(function() {
$(document).mousemove(function(e) {
// assign the co-ords as vars so
var vert = e.pageY;
var horz = e.pageX;
// get co -ords for the center of the box
centx = Math.ceil($('div').width() / 2);
centy = Math.ceil($('div').height() / 2);
// checking to see if the cursor is outside the boudries of the box and stoping the circle moving past them
if (e.pageY + 53 > Math.ceil($('div').height())) var vert = Math.ceil($('div').height() - 47);
if (e.pageY - 53 < 0) vert = 53;
if (e.pageX + 53 > Math.ceil($('div').width())) var horz = Math.ceil($('div').width() - 47);
if (e.pageX - 53 < 0) horz = 53;
// work out the distance between the cursor and the center of box
disx = horz - centx;
disy = vert - centy;
// work out the scale of the shadow
sx = -disx * 0.1;
sy = -disy * 0.1;
// work out the shadow blur
b = (Math.abs(sx) + Math.abs(sy)) * 0.5;
//apply the css
$('p').css({
'top': vert - 53,
'left': horz - 53,
'-webkit-box-shadow': '#a0a0a0 ' + sx + 'px ' + sy + 'px ' + b + 'px, inset ' + sx + 'px ' + sy + 'px ' + b + 'px #e3e3e3'
});
});
});
body {
padding: 0px;
}
div {
position: relative;
width: 400px;
height: 400px;
background-color: #f0f0f0;
}
p {
background-color: orange;
height: 100px;
width: 100px;
position: absolute;
top: 100px;
left: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<div>
<p>set the location</p>
</div>
fiddle
edit
To restrict movement once the box is clicked, just use a helper variable:
var cond = false;
$(yourElement).click(function () {
cond = true;
})
Then, in the body of your mousemove function:
if (cond) return false;
You should check whether the mouse is within the div using Element.getBoundingClientRect:
var boundary = document.getElementById("theDiv").getBoundingClientRect()
var vert = e.pageY;
var horz = e.pageX;
if (boundary.top <= vert && vert <= boundary.bottom &&
boundary.left <= horz && horz <= boundary.right) {
/* the rest of your code */
}
Element.getBoundingClientRect returns an object like this:
{
bottom: 408,
height: 400,
left: 8,
right: 408,
top: 8,
width: 400,
}
If you want to use jQuery, you can instead use
var left = $(item).offset().left
, top = $(item).offset().top
, right = left + $(item).width()
, bottom = top + $(item).height()
;
and set up a similar if condition.
demo:
$(function() {
var cond = false;
$("#theDiv").click(function () {
cond = true;
})
$(document).mousemove(function(e) {
if (cond) return false;
var boundary = document.getElementById("theDiv").getBoundingClientRect()
// assign the co-ords as vars so
var vert = e.pageY;
var horz = e.pageX;
if (boundary.top <= vert && vert <= boundary.bottom && boundary.left <= horz && horz <= boundary.right) {
// get co -ords for the center of the box
centx = Math.ceil($('div').width() / 2);
centy = Math.ceil($('div').height() / 2);
// checking to see if the cursor is outside the boudries of the box and stoping the circle moving past them
if (e.pageY + 53 > Math.ceil($('div').height())) var vert = Math.ceil($('div').height() - 47);
if (e.pageY - 53 < 0) vert = 53;
if (e.pageX + 53 > Math.ceil($('div').width())) var horz = Math.ceil($('div').width() - 47);
if (e.pageX - 53 < 0) horz = 53;
// work out the distance between the cursor and the center of box
disx = horz - centx;
disy = vert - centy;
// work out the scale of the shadow
sx = -disx * 0.1;
sy = -disy * 0.1;
// work out the shadow blur
b = (Math.abs(sx) + Math.abs(sy)) * 0.5;
//apply the css
$('p').css({
'top': vert - 53,
'left': horz - 53,
'-webkit-box-shadow': '#a0a0a0 ' + sx + 'px ' + sy + 'px ' + b + 'px, inset ' + sx + 'px ' + sy + 'px ' + b + 'px #e3e3e3'
});
}
});
});
body {
padding: 0px;
}
div {
position: relative;
width: 400px;
height: 400px;
background-color: #f0f0f0;
}
p {
background-color: orange;
height: 100px;
width: 100px;
position: absolute;
top: 100px;
left: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="theDiv">
<p>set the location</p>
</div>
fiddle

Categories