Francesca Francesca - 15 days ago 12x
CSS Question

Mousemove parallax effect moves position of div

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:

It achieves this by shifting the background position on the
div when the mouse moves.

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
shift, but on a
position shift. E.g
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?


How about using jQuert.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 });