Search code examples
javascriptjquerymootools

Eyes follow mouse cursor Mootools -> JQuery


I was looking for some code to help me make eyes on a page follow the cursor, there are a few examples around but this one caught my eye: https://github.com/Goutte/Eye mainly because it requires so little code.

It uses mootools which I have never looked at before, is it possible to convert this to use jQuery or can someone explain exactly how this is working with so little javascript? What functions does mootools have built in that allows this to be so simple?

JsFiddle: http://jsfiddle.net/B2Nza/46/

var options2 = {
  socketRadius: 2, // radius of the circle in which the eye's pupil can move
  bindTouchMove: true,
}

var leftEye2  = new Eye ('left_eye2', options2);
var rightEye2 = new Eye ('right_eye2', options2);

var fly2 = new Eye ('fly2', {
    socketRadius: 17,
    behavior: 'follow',
    stickToSocket: true
});

Solution

  • Here is how you can do it with JavaScript.

    var element = document.getElementById("leela-eye");
    document.addEventListener("mousemove", function (event) {
        var x = event.pageX;
        var y = event.pageY;   
        var offsets = eye.lens.getBoundingClientRect();
        var left = (offsets.left - x)
        var top = (offsets.top - y)
        var rad = Math.atan2(top, left);
        element.style.webkitTransform = "rotate(" + rad + "rad)";
    });
    

    jsFiddle.

    If you browser doesn't support passing radians to rotate(), you can convert it to degrees (and swap rad with deg in the property value).

    var deg = rad * (180 / Math.PI);