javascript - jQuery multiple parallax buttons -
i've got bunch of divs on single page of same type used buttons. have same class box
, each it's own unique content.
i'm trying them move away mouse ever create slight parallax effect. i'm having trouble making them move independently each other.
currently, 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, grab location of each box element it's x , y position. event supposed cursor's position math generate parallax effect based on initial position of box.
now know why doesn't work, because on line css, i'm using .box
applies every box element on page position of last declared box. original intention use this
in it's place, refers html
used when starting mousemove
function, want access instance of box
above it.
what need make boxes move independently each other?
this script moves boxes independently amount of independent movement small (see below).
jquery
$('html').on("mousemove", function(event) { var mousex = event.pagex; var mousey = event.pagey; $('.box').each(function( ) { var location = $(this).offset(); var locationx = location.left; var locationy = location.top; var offsety = ( locationy - mousey ) / 40; var offsetx = ( locationx - mousex ) / 30; //console.log( + ' locationx: ' + locationx ); $( ).css('transform', 'translate3d(' + offsetx + 'px, ' + offsety + 'px, 0)'); }); });
rendered html 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 parallax math? is, since boxes aligned vertically have same offsety , never move relative each other in dimension. locationx differs 200px , if divide 50 can move 4px relative each other. think offset calculation needs more complexity.
codepen: http://codepen.io/steveclason/pen/jkjwvb?editors=1111
Comments
Post a Comment