How do I set the borders in which I want my children to move when following the cursor on a movement?
I am making a project in which I have to add some googly eyes to a face in jQuery. I have the design in CSS and my divs in HTML I now want to add the mouse movement with Jquery. I found a very helpful answer on this site and I managed to make the pupils follow the cursor but they move all over the screen not just in the eyeballs. I searched for codes that have the same result but they are either javascript codes or the movement is made with hover in CSS. To me that looked complicated so I thought I could just ask here if anyone knows how to define the area in which I want my pupils to move. In my case I want pupilsRight/Left to move inside divs :#leftEye respectively #rightEye not all over the screen.
$(document).ready(function() {
var leftPupil = $("<div><div>");
$("#leftye").append(leftPupil);
var rightPupil = $("#rightEye div div");
$("#rightEye").append(rightPupil);
rightPupil.show();
$(window).on('mousemove', function(e){
pupilleLinks.css({
left: e.pageX,
top: e.pageY
});
pupilleRechts.css({
left: e.pageX,
top: e.pageY
});
});
});
</script>
</head>
<b
<div style="float:left;font-weight:bold;">Deine Spielwiese:</div>
<div id="face">
<div id="leftEye">Left Eye</div>
<div id="rightEye" >Right Eye<div>
<span></span>
<div style="display:none;background-color:#000;width:20px;height:20px;border-radius:10px;position:absolute;bottom:10px;lef:10px;"></div>
</div>
</div>
<div style="display:none;border:1px solid green;width:35px;height:35px;margin-top:70px; display: inline-block; border-radius:35px;background-color:#DFD;"></div
I did not copy all CSS part because it was pretty long. If someone has an idea how i could define the wanted movement area that would be great.
Your code didn't work at all, so I first misunderstood what you meant. I couldn't pick up much from your broken code so I quickly rewrote it.
Markup for each eye:
<div class="eye">
<div class="roller">
<div class="pupil"></div>
</div>
</div>
What you should do is:
- calculate the distance from your mouse to your eye's center
- limit the distance to the radius of your eye
- calculate the angle of the line that your mouse and the center of the eye would form
- set
.pupil
to the right distance from the center and rotate the.roller
element
Here's the fiddle with some more detailed explanation: https://jsfiddle.net/ilpo/zyx0ag9z/1/
Also, it works with any number of eyes at any size: https://jsfiddle.net/ilpo/zyx0ag9z/3/
And you'll only have to change the eye's height
and width
- the pupils' sizes and everything else scale automatically!