I've got a bunch of divs on a single page that are all of the same type to be used as buttons. They all currently have the same class box
, each with it's own unique content.
I'm trying to get them to move away from the mouse ever so slightly to create a slight parallax effect. But I'm having trouble making them move independently from each other.
Currently, this is what I've tried:
$(function() {
$('.box').each(function() {
var location = $(this).offset();
var locationX = location.left;
var locationY = location.top;
$('html').on("mousemove", function(event) {
var offsetX = (locationX - event.pageX) / 100;
var offsetY = (locationY - event.pageY) / 100;
$('.box').css('transform', 'translate3d(' + offsetX + 'px, ' + offsetY + 'px, 0)');
});
});
});
So basically, I grab the location of each box element to which I get it's X and Y position. Then the event is supposed to get the cursor's position then do some math to generate the parallax effect based on the initial position of the box.
Now I know why this doesn't work, because on the line with the css, I'm using .box
which applies to every box element on the page to position of the last declared box. My original intention was to use this
in it's place, but it then refers to html
which is used when starting the mousemove
function, but I really want to access the instance of box
just above it.
What do I need to do to make the boxes move independently from each other?
This script moves the boxes independently but the amount of independent movement is small (see below).
jQuery
$('html').on("mousemove", function(event) {
var mouseX = event.pageX;
var mouseY = event.pageY;
$('.box').each(function( i ) {
var location = $(this).offset();
var locationX = location.left;
var locationY = location.top;
var offsetY = ( locationY - mouseY ) / 40;
var offsetX = ( locationX - mouseX ) / 30;
//console.log( i + ' locationX: ' + locationX );
$( this ).css('transform', 'translate3d(' + offsetX + 'px, ' + offsetY + 'px, 0)');
});
});
Rendered html from devtools:
<body translate="no">
<div class="box" style="top: 50px; left: 50px; transform: translate3d(-27.3027px, -0.854667px, 0px);">
Box 1
</div>
<div class="box" style="top: 50px; left: 250px; transform: translate3d(-23.2213px, -0.854667px, 0px);">
Box 2
</div>
<div class="box" style="top: 50px; left: 450px; transform: translate3d(-19.1397px, -0.854667px, 0px);">
Box 3
</div>
</body>
So maybe re-calculating the parallax math? That is, since the boxes are aligned vertically they will always have the same offsetY and so will never move relative to each other in that dimension. Their locationX differs by 200px and if you divide that by 50 they can only move 4px relative to each other. I think your offset calculation needs more complexity.
Codepen: http://codepen.io/SteveClason/pen/JKjWVB?editors=1111