Greetings
As I delved into creating a function that would cause a particular behavior (the closer you move the mouse to a div, the closer the div moves to the mouse position on the parent's X axis, with a maximum div position of left:-40% and a minimum of left:-80%):
Important: The black arrow symbolizes the cursor (mouse position).
Code Snippet
HTML markup:
<div class="wraper">
<div class="ls">
<div class="ldiv">
</div>
</div>
<div class="c">
<div class="coordinates">
</div>
<div class="cdiv">
</div>
</div>
<div class="rs">
<div class="rdiv">
</div>
</div>
</div>
CSS markup:
body{
margin: 0;
padding: 0;
}
.wraper{
width: 100%;
height: 500px;
}
.ls, .rs{
position: relative;
float: left;
width: 30%;
height: 100%;
background-color: #eeeeee;
}
.c{
position: relative;
float: left;
width: 40%;
height: 100%;
background-color: #dddddd;
}
.cdiv{
position: absolute;
top: 25%;
left: 10%;
width: 80%;
height: 50%;
background-color: red;
}
.ldiv{
position: absolute;
top: 30%;
left: -80%;
width: 80%;
height: 40%;
background-color: red;
}
.rdiv{
position: absolute;
top: 30%;
right: -40%;
width: 80%;
height: 40%;
background-color: red;
}
Javacsript markup:
//Assigning global variables
var mouseX = 0;
var newTop = 0;
$("div.ls").mousemove(function(event) {
// Getting parent offset
var parentOffset = $(this).offset();
// Getting child division offset
var division = $(".ldiv").offset();
// Calculating mouse position inside left division
var relX = event.pageX - parentOffset.left;
var relY = event.pageY - parentOffset.top;
// Checking for any mouse position changes
if (mouseX != relX){
// Finding the new position of x-axis
var newPosX = $(this).width() - relX - 161;
// Calculating new height of child element in percentage
var newHeight = 100 * parseFloat($(".ldiv").height()) / parseFloat($(this).height());
// Displaying relevant information
$(".coordinates").text("Mouse position = X:" + relX + " Y:" + relY + "Div offset = X:" + division.left + " Y:" + division.top + " Width = " + $(this).width()+" newHeight = "+newHeight);
// If the mouse moves left
if (mouseX > relX) {
// Making sure it doesn't go lower than 0.2 due to JavaScript rounding
newHeight += 0.2;
// Calculating new top so division stays in the middle of parent
newTop = (100 - newHeight) / 2;
// Applying new CSS
$(".ldiv").css({
left: newPosX + "px",
height: newHeight + "%",
top: newTop + "%"
});
}
// If the mouse moves right
else {
newHeight -= 0.2;
newTop = (100 - newHeight) / 2;
$(".ldiv").css({
left: newPosX + "px",
height: newHeight + "%",
top: newTop + "%"
});
}
// Recording the mouse position
mouseX = relX;
}
});
Check out a live example on jsFiddle
Goals I aim to achieve:
- How can I refactor this code to work more smoothly as an animation, without glitches when moving the mouse too quickly?