Mousemove parallax effect moves position of div

Francesca picture Francesca · Jun 10, 2015 · Viewed 28.9k times · Source

I'm trying to create a slight parallax effect (I'm not sure if it really constitutes parallax but it's a similar idea). Where there are four layers which all move around at a slightly different rate when the mouse moves.

I have found a great example that offers something similar to what I want:

http://jsfiddle.net/X7UwG/2/

It achieves this by shifting the background position on the #landing-content div when the mouse moves.

$(document).ready(function(){
  $('#landing-content').mousemove(function(e){
    var x = -(e.pageX + this.offsetLeft) / 20;
    var y = -(e.pageY + this.offsetTop) / 20;
    $(this).css('background-position', x + 'px ' + y + 'px');
  });  
});

However, I cannot work out a way to get this to work not on a background-position shift, but on a div position shift. E.g position:relative; and top:x so that the div itself moves around a little.

My reasoning is that the div contains CSS animation elements so it needs to be a div with content inside it, not a background image.

Any solutions for this using the code above?

Answer

Josh Bilderback picture Josh Bilderback · Jun 10, 2015

How about using jQuery.offSet() instead? You might want to adjust the math/values, but I think it should set you in the right direction.

$(document).ready(function () {
    $('#layer-one').mousemove(function (e) {
        parallax(e, this, 1);
        parallax(e, document.getElementById('layer-two'), 2);
        parallax(e, document.getElementById('layer-three'), 3);
    });
});

function parallax(e, target, layer) {
    var layer_coeff = 10 / layer;
    var x = ($(window).width() - target.offsetWidth) / 2 - (e.pageX - ($(window).width() / 2)) / layer_coeff;
    var y = ($(window).height() - target.offsetHeight) / 2 - (e.pageY - ($(window).height() / 2)) / layer_coeff;
    $(target).offset({ top: y ,left : x });
};

JSFiddle: http://jsfiddle.net/X7UwG/854/