Inverse Box Movement

Uses jQuery to create and inversely moving div in relation to the user's mouseX and mouseY coordinates

by mmansion

HTML

<input class="info" type="text" disabled>

<section class="area">
    
    <div class="box"></div>
    
</section>

CSS

html, body {
    margin: 0;
}
.info {
    position: absolute;
    z-index: 99;
}
.box {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -50px;
    margin-left: -50px;
    width: 100px;
    height: 100px;
    background: red;
}
.box:hover {
    background: orange;
    cursor: pointer;
}

.area {
    position: absolute;
    width: 100%;
    height: 100%;
    background: black;
}

JavaScript

var mouseX = 0;
var mouseY = 0;

//get offset values for centering coords
var offsetWidth  = $('.area').width()/2;
var offsetHeight = $('.area').height()/2;

//store the original box x and y values
var origBoxTop  = parseInt($('.box').css('top'));
var origBoxLeft = parseInt($('.box').css('left'));


$('.area').mousemove( function(e) {
   //get x and y for mouse, offset to center
   mouseX = offsetWidth  - e.pageX; 
   mouseY = offsetHeight - e.pageY;
   
   //inverse scrolling
   $('.box').css('top',  origBoxTop + mouseY);
   $('.box').css('left', origBoxLeft + mouseX);
    
   //print the mouse coords
   $('.info').attr('value', 'x: ' + mouseX + ', y: ' + mouseY);
 });