Search code examples
jqueryeffect

Move an image to and from effect with jQuery


I really like the effect of movement of the spaceship when you move your mouse. Does anyone know how can this effect be achieved with jQuery?

Here's the link: http://spaceexpeditions.xcor.com/


Solution

  • You can use this simple code

    $(window).mousemove(function(e){
        var clientX = e.clientX;
        var clientY = e.clientY;
        
        var width = $(window).width();
        var height = $(window).height();
        
        var constWidth = (width / 2) - $("div").width();
        var constHeight = (height / 2) - $("div").height();   
        
        $("div").css({
            left: constWidth + ((constWidth - clientX) / 10),
            top: constHeight + ((constHeight - clientY) / 10)        
        });  
    });
    body {
        position: relative;
    }
    
    div {
        width: 50px;
        height: 50px;
        background: blue;
        position: absolute;
        top: 50px;
        left: 300px;
        -webkit-transition: all 0.15s;
        transition: all 0.15s;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div></div>

    See better result of example in jsfiddle