Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 554
Francesca Avatar asked Jun 10 '15 15:06

Francesca


1 Answers

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/

like image 200
Josh Bilderback Avatar answered Oct 21 '22 11:10

Josh Bilderback